#override
Widget build(BuildContext context) {
var switchButton = new Switch(
value: detail,
onChanged: (bool value){
setState(() {
detail = value;
});
},
);
var imagejadwal = new CachedNetworkImage(
imageUrl: switchButton.value?"https://drive.google.com/uc?export=download&id=1v-dA5bG7Fwk_hJvL2wu4Z9P10JdsaWIe":"https://drive.google.com/uc?export=download&id=1qfdI_yM7rzdLMqRizlr76445qc0IQKhD",
placeholder: new CircularProgressIndicator(),
errorWidget: new Icon(Icons.error),
);
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Column(
children: <Widget>[
new Align(
alignment: Alignment.topRight,
child: switchButton,
),
imagejadwal,
],
)
);
}
It's because the CachedNetworkImage or my code is wrong ? Can someone
help me ? I'm still new at flutter Thank you.
Lib: https://github.com/renefloor/flutter_cached_network_image
I tried the code of aziza, but it also didn't work for me.
I changed a bit of code in the CachedNetworkImage and that seems to work, I changed the 'didUpdateWidget':
#override
void didUpdateWidget(CachedNetworkImage oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.imageUrl != oldWidget.imageUrl ||
widget.placeholder != widget.placeholder){
_imageProvider = new CachedNetworkImageProvider(widget.imageUrl,
errorListener: _imageLoadingFailed);
_resolveImage();
}
}
It needs to change its ImageProvider. I made an issue for that on github
You could also use a Stack. In that way you have more control over the animation from one image to the other. For example
class _CachedImageExampleState extends State<CachedImageExample> {
bool switchState = true;
#override
Widget build(BuildContext context) {
var switchButton = new Switch(
value: switchState,
onChanged: (bool value) {
setState(() {
switchState = value;
});
},
);
var imagejadwal1 = new CachedNetworkImage(
imageUrl: "https://drive.google.com/uc?export=download&id=1v-dA5bG7Fwk_hJvL2wu4Z9P10JdsaWIe",
placeholder: new CircularProgressIndicator(),
errorWidget: new Icon(Icons.error),
);
var imagejadwal2 = new CachedNetworkImage(
imageUrl: "https://drive.google.com/uc?export=download&id=1qfdI_yM7rzdLMqRizlr76445qc0IQKhD",
placeholder: new CircularProgressIndicator(),
errorWidget: new Icon(Icons.error),
);
return new Scaffold(
appBar: new AppBar(
title: new Text("TestImage"),
),
body: new Column(
children: <Widget>[
new Align(
alignment: Alignment.topRight,
child: switchButton,
),
new Container (
//width: 500.0,
///container to deal with the overflow, you may not want to use it with hardcoded
///height because it will not allow the view to be responsive, but it is just to
///make a point about dealing with the overflow
height: 400.0,
child: new Stack(children: <Widget>[
new Opacity(opacity: switchState ? 1.0 : 0.0, child: imagejadwal1),
new Opacity(opacity: switchState ? 0.0 : 1.0, child: imagejadwal2,)
],)),
],
)
);
}
}
I noticed that the animation of the switch is not shown when the second image (the blue one) is being shown. It is a very large image (2550x3300), consider making that one smaller to improve the performance of the app.
Your code is working fine, however you have got two issue to deal with:
The images are overflowing and may be preventing the UI from updating.
The images are too big, and you need to wait a little bit for them to load.
I have modified a little bit of your code:
class _CachedImageExampleState extends State<CachedImageExample> {
bool switchState = true;
#override
Widget build(BuildContext context) {
var switchButton = new Switch(
value: switchState,
onChanged: (bool value) {
setState(() {
switchState = value;
});
},
);
var imagejadwal = new CachedNetworkImage(
imageUrl: switchState
? "https://drive.google.com/uc?export=download&id=1v-dA5bG7Fwk_hJvL2wu4Z9P10JdsaWIe"
: "https://drive.google.com/uc?export=download&id=1qfdI_yM7rzdLMqRizlr76445qc0IQKhD",
placeholder: new CircularProgressIndicator(),
errorWidget: new Icon(Icons.error),
);
return new Scaffold(
appBar: new AppBar(
title: new Text("TestImage"),
),
body: new Column(
children: <Widget>[
new Align(
alignment: Alignment.topRight,
child: switchButton,
),
new Container (
//width: 500.0,
///container to deal with the overflow, you may not want to use it with hardcoded
///height because it will not allow the view to be responsive, but it is just to
///make a point about dealing with the overflow
height: 400.0,
child: imagejadwal),
],
)
);
}
}
I managed to fix your issue, there are two implementations for this plugin and the following one should fix it for you. I am not sure the reason behind state not updating (probably imageUrl can not be overriden)
Anyway, here is your fix:
class CachedImageExample extends StatefulWidget {
#override
_CachedImageExampleState createState() => new _CachedImageExampleState();
}
class _CachedImageExampleState extends State<CachedImageExample> {
bool toggle = true;
#override
Widget build(BuildContext context) {
var switchButton = new Switch(
value: toggle,
onChanged: (bool value) {
setState(() {
toggle = value;
});
},
);
var img= new Image(image: new CachedNetworkImageProvider(
toggle
? "https://drive.google.com/uc?export=download&id=1v-dA5bG7Fwk_hJvL2wu4Z9P10JdsaWIe"
: "https://drive.google.com/uc?export=download&id=1qfdI_yM7rzdLMqRizlr76445qc0IQKhD"));
return new Scaffold(
appBar: new AppBar(
title: new Text("TestImage"),
),
body: new Column(
children: <Widget>[
new Align(
alignment: Alignment.topRight,
child: switchButton,
),
new Container (
width: 200.0,
height: 200.0,
child: img),
],
)
);
}
}
Update : Fit the image to the whole screen
class CachedImageExample extends StatefulWidget {
#override
_CachedImageExampleState createState() => new _CachedImageExampleState();
}
class _CachedImageExampleState extends State<CachedImageExample> {
bool toggle = true;
#override
Widget build(BuildContext context) {
var switchButton = new Switch(
activeColor: Colors.amber,
activeTrackColor: Colors.amberAccent,
inactiveThumbColor: Colors.amber,
value: toggle,
onChanged: (bool value) {
setState(() {
toggle = value;
});
},
);
return new Scaffold(
appBar: new AppBar(
actions: <Widget>[
switchButton
],
title: new Text("TestImage"),
),
body:
new Container (
decoration: new BoxDecoration(
image: new DecorationImage(
fit: BoxFit.cover,
image:
new CachedNetworkImageProvider(
toggle
? "https://drive.google.com/uc?export=download&id=1v-dA5bG7Fwk_hJvL2wu4Z9P10JdsaWIe"
: "https://drive.google.com/uc?export=download&id=1qfdI_yM7rzdLMqRizlr76445qc0IQKhD"
)
),
),
),
);
}
}
Related
I am trying to implement Flutter's Tab Bar with 3 tabs and an AnimatedList inside those tabs. I want to use the same list and filter the list according to each tab (past tasks, today's tasks, and future tasks), however during my implementation of the tab bar together with the animatedlist I am getting an error regarding a duplicate global key in the widget tree. https://pastebin.com/iAW6DH9m . What would be the best way to deal with this error? Thank you for any help.
edit: I tried using this method to fix this. Multiple widgets used the same GlobalKey while it did fix my error I was then unable to access "currentstate" method on the key to be able to add more items to the list. I then tried a similar method using using GlobalKey and it resulted in a similar error of duplicate global keys.
This is my tab bar implementation
import 'package:flutter/material.dart';
import 'search_widget.dart';
import 'animatedlist_widget.dart';
class Dashboard extends StatefulWidget {
#override
_DashboardState createState() => _DashboardState();
}
class _DashboardState extends State<Dashboard> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
centerTitle: true,
actions: <Widget>[
new IconButton(icon: new Icon(Icons.grid_on), onPressed: null)
],
title: new Text('Dashboard'),
elevation: 0,
),
floatingActionButton: new FloatingActionButton(
onPressed: () {
_onFabPress(context);
},
child: new Icon(Icons.add)),
body: Scaffold(
appBar: new SearchWidget(
onPressed: () => print('implement search'),
icon: Icons.search,
title: 'Search',
preferredSize: Size.fromHeight(50.0),
),
body: DefaultTabController(
length: 3,
child: Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(kToolbarHeight),
child: Container(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: new TabBar(
unselectedLabelColor: Colors.black45,
labelColor: Colors.white,
indicator: CustomTabIndicator(),
tabs: <Widget>[
new Tab(text: "Past"),
new Tab(text: "Today"),
new Tab(text: "Future")
]),
),
),
),
body: new TabBarView(
children: <Widget>[
AnimatedTaskList(),
AnimatedTaskList(),
AnimatedTaskList()
],
)
),
),
),
);
}
void _onFabPress(context) {
AnimatedTaskList().addUser();
}
/*showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return Container(
child: new Wrap(children: <Widget>[
new TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter Task Title')),
new TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter Task Details',
)),
]));
});
}*/
}
class CustomTabIndicator extends Decoration {
#override
BoxPainter createBoxPainter([onChanged]) {
// TODO: implement createBoxPainter
return new _CustomPainter(this, onChanged);
}
}
class _CustomPainter extends BoxPainter {
final CustomTabIndicator decoration;
_CustomPainter(this.decoration, VoidCallback onChanged)
: assert(decoration != null),
super(onChanged);
#override
void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
// TODO: implement paint
assert(configuration != null);
assert(configuration.size != null);
final indicatorHeight = 30.0;
final Rect rect = Offset(
offset.dx, (configuration.size.height / 2) - indicatorHeight / 2) &
Size(configuration.size.width, indicatorHeight);
final Paint paint = Paint();
paint.color = Colors.blueAccent;
paint.style = PaintingStyle.fill;
canvas.drawRRect(RRect.fromRectAndRadius(rect, Radius.circular(30)), paint);
}
}
This is my animatedlist class:
import 'package:flutter/material.dart';
final GlobalKey<AnimatedListState> _listKey = GlobalKey();
class AnimatedTaskList extends StatefulWidget {
void addUser() {
int index = listData.length;
listData.add(
TaskModel(
taskTitle: "Grocery Shopping",
taskDetails: "Costco",
),
);
_listKey.currentState
.insertItem(index, duration: Duration(milliseconds: 500));
}
#override
_AnimatedTaskListState createState() => _AnimatedTaskListState();
}
class _AnimatedTaskListState extends State<AnimatedTaskList> {
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: SafeArea(
child: AnimatedList(
key: _listKey,
initialItemCount: listData.length,
itemBuilder:
(BuildContext context, int index, Animation animation) {
return Card(
child: FadeTransition(
opacity: animation,
child: ListTile(
title: Text(listData[index].taskTitle),
subtitle: Text(listData[index].taskDetails),
onLongPress: () {
//todo delete user
},
)));
})),
);
}
}
class TaskModel {
TaskModel({this.taskTitle, this.taskDetails});
String taskTitle;
String taskDetails;
}
List<TaskModel> listData = [
TaskModel(
taskTitle: "Linear Algebra",
taskDetails: "Chapter 4",
),
TaskModel(
taskTitle: "Physics",
taskDetails: "Chapter 9",
),
TaskModel(
taskTitle: "Software Construction",
taskDetails: "Architecture",
),
];
I fixed my issue by moving
final GlobalKey<AnimatedListState> _listKey = GlobalKey();
into my _AnimatedTaskListState class, and adding a constructor and private key to my AnimatedTaskList class
final GlobalKey<AnimatedListState> _key;
AnimatedTaskList(this._key);
#override
_AnimatedTaskListState createState() => _AnimatedTaskListState(_key);
then in my tab bar implementation I changed it to reflect my new constructor
AnimatedTaskList(GlobalKey<AnimatedListState>(debugLabel: "key 1"));
AnimatedTaskList(GlobalKey<AnimatedListState>(debugLabel: "key 2"));
AnimatedTaskList(GlobalKey<AnimatedListState>(debugLabel: "key 3"));
I'm using the webview_fluttter plugin, but I can't find a way to show a CircularProgressIndicator before the webview shows the page...
What's the equivalent of Androids WebViewClient onPageStarted/onPageFinished?
WebView(
initialUrl: url,
onWebViewCreated: (controller) {
},
)
In version 0.3.5 there is 'onPageFinished' callback. You can create WebView container with IndexedStack.
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class _WebViewContainerState extends State < WebViewContainer > {
var _url;
final _key = UniqueKey();
_WebViewContainerState(this._url);
num _stackToView = 1;
void _handleLoad(String value) {
setState(() {
_stackToView = 0;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: IndexedStack(
index: _stackToView,
children: [
Column(
children: < Widget > [
Expanded(
child: WebView(
key: _key,
javascriptMode: JavascriptMode.unrestricted,
initialUrl: _url,
onPageFinished: _handleLoad,
)
),
],
),
Container(
color: Colors.white,
child: Center(
child: CircularProgressIndicator(),
),
),
],
)
);
}
}
class WebViewContainer extends StatefulWidget {
final url;
WebViewContainer(this.url);
#override
createState() => _WebViewContainerState(this.url);
}
This is working properly for me
initState() {
isLoading = true;
};
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: Text("Your Title",centerTitle: true
),
body: Stack(
children: <Widget>[
new WebView(
initialUrl: /* YourUrl*/,
onPageFinished: (_) {
setState(() {
isLoading = false;
});
},
),
isLoading ? Center( child: CircularProgressIndicator()) : Container(),
],
),
);
}
class _WebViewContainerState extends State<WebViewContainer> {
var _url;
final _key = UniqueKey();
bool _isLoadingPage;
Completer<WebViewController> _controller = Completer<WebViewController>();
_WebViewContainerState(this._url);
#override
void initState() {
super.initState();
_isLoadingPage = true;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
new WebView(
key: _key,
initialUrl: _url,
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (webViewCreate) {
_controller.complete(webViewCreate);
},
onPageFinished: (finish) {
setState(() {
_isLoadingPage = false;
});
},
),
_isLoadingPage
? Container(
alignment: FractionalOffset.center,
child: CircularProgressIndicator(),
)
: Container(
color: Colors.transparent,
),
],
),
);
}
}
Optional parameters hidden and initialChild are available so that you can show something else while waiting for the page to load.If you set hidden to true it will show a default CircularProgressIndicator. If you additionally specify a Widget for initialChild you can have it display whatever you like till page-load.
check this page : flutter_webview_plugin
and you can specify what you want to show with initialChild
return new MaterialApp(
title: 'Flutter WebView Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
routes: {
'/': (_) => const MyHomePage(title: 'Flutter WebView Demo'),
'/widget': (_) => new WebviewScaffold(
url: selectedUrl,
appBar: new AppBar(
title: const Text('Widget webview'),
),
withZoom: true,
withLocalStorage: true,
hidden: true,
initialChild: Container(
child: const Center(
child: CircularProgressIndicator(),
),
),
),
},
);
I use a combination of webview_flutter, progress_indicators
Here is a sample working code:
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:async';
import 'package:progress_indicators/progress_indicators.dart';
class ContactUs extends StatefulWidget {
#override
_ContactUsState createState() => _ContactUsState();
}
class _ContactUsState extends State<ContactUs> {
bool vis1 = true;
Size deviceSize;
#override
Widget build(BuildContext context) {
deviceSize = MediaQuery.of(context).size;
final lindicator = Center(
child: AnimatedOpacity(
// If the Widget should be visible, animate to 1.0 (fully visible). If
// the Widget should be hidden, animate to 0.0 (invisible).
opacity: vis1 ? 1.0 : 0.0,
duration: Duration(milliseconds: 500),
// The green box needs to be the child of the AnimatedOpacity
child: HeartbeatProgressIndicator(
child: Container(
width: 100.0,
height: 50.0,
padding: EdgeInsets.fromLTRB(35.0,0.0,5.0,0.0),
child: Row(
children: <Widget>[
Icon(
Icons.all_inclusive, color: Colors.white, size: 14.0,),
Text(
"Loading View", style: TextStyle(color: Colors.white, fontSize: 6.0),),
],
),
),
),
),
);
return new Scaffold(
appBar: new AppBar(
title: new Row(
children:<Widget>[
Text('THisApp'),
lindicator,
]),
backgroundColor: Colors.red,
),
body: new Container(
child:WebView(
initialUrl: 'https://cspydo.com.ng/',
javaScriptMode: JavaScriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController){
setState(() {
vis1=false;
});
},
)
),
);
}
}
Found the solution.You can add initialChild and set attribute hidden as true.
WebviewScaffold(
hidden: true,
url:url,initialChild: Center(
child: Text("Plase Wait...",style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.deepPurpleAccent[100]
),)
) )
You can work on isLoading and change it after you are sure data is loaded properly.
class X extends StatefulWidget {
XState createState() => XState();
}
class XState extends State<X>{
bool isLoading = false;
#override
void initState() {
setState(() {
isLoading = true;
});
super.initState();
}
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
isLoading ? Center(child: CircularProgressIndicator()) : WebView(...)
]
)
);
}
}
I used A stack in flutter.
#override
void initState() {
isLoading = true;
super.initState();
}
in the build method
Stack(
children: [
isLoading ? Loading() : Container(),
Container(
child: Flex(
direction: Axis.vertical,
children: [
Expanded(
child: InAppWebView(
contextMenu: contextMenu,
initialUrl: url,
onLoadSop: (InAppWebViewController controller, url) {
setState(() {
isLoading = false;
});
},
)
),
],
),
),
],
)
When using the following Switch widget, the isOn value always returns true and never changes.
The Switch only moves position on a swipe too, a tap won't move it. How to resolve?
bool isInstructionView = false;
Switch(
value: isInstructionView,
onChanged: (bool isOn) {
setState(() {
isInstructionView = isOn;
print(isInstructionView);
});
},
activeColor: Colors.blue,
inactiveTrackColor: Colors.grey,
inactiveThumbColor: Colors.grey,
)
Update: For extra clarity, onChanged always returns isOn as true. Why would this be?
I added additional code chunks according to #Zulfiqar 's answer. I didn't test this code but I m using similar codes in my project. if you want to save it and use in another class or if you want to show latest state for everytime you load you can save the state in a global variable and call it when you load the class. hope it will help..
class Tab_b extends StatefulWidget {
#override
State<StatefulWidget> createState() => new _TabsPageState();
}
class _TabsPageState extends State<Tab_b>{
bool isInstructionView;
#override
void initState() {
isInstructionView = Global.shared.isInstructionView;
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text("add data"),
),
body: new Container(
child: Switch(
value: isInstructionView,
onChanged: (bool isOn) {
print(isOn);
setState(() {
isInstructionView = isOn;
Global.shared.isInstructionView = isOn;
isOn =!isOn;
print(isInstructionView);
});
},
activeColor: Colors.blue,
inactiveTrackColor: Colors.grey,
inactiveThumbColor: Colors.grey,
),
),
);
}
}
class Global{
static final shared =Global();
bool isInstructionView = false;
}
You just need to make sure to declare the bool for the switch toggle outside Widget build to make it global and acessible for SetState method. No need to initstate and etc.
class ExampleClass extends StatefulWidget {
#override
_ExampleClassState createState() => _ExampleClassState();
}
class _ExampleClassState extends State<ExampleClass> {
bool isInstructionView = false;
#override
Widget build(BuildContext context) {
return Container(
child: Switch(
value: isInstructionView,
onChanged: (isOn) {
setState(() {
isInstructionView = isOn
});
print(isInstructionView);
},
...
),
);
}
}
class Tab_b extends StatefulWidget {
bool isInstructionView = false;
#override
State<StatefulWidget> createState() => new _TabsPageState();
}
class _TabsPageState extends State<Tab_b>{
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text("add data"),
),
body: new Container(
child: Switch(
value: widget.isInstructionView,
onChanged: (bool isOn) {
print(isOn);
setState(() {
widget.isInstructionView = isOn;
print(widget.isInstructionView);
});
},
activeColor: Colors.blue,
inactiveTrackColor: Colors.grey,
inactiveThumbColor: Colors.grey,
),
),
);
}
Here Is my code for toggle button
class ToggleButtonScreen extends StatefulWidget {
#override
_ToggleButtonScreenState createState() => _ToggleButtonScreenState();
}
class _ToggleButtonScreenState extends State<ToggleButtonScreen> {
bool _value = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: _value ? AssetImage("images/cnw.png") : AssetImage("images/cnw.png"),
fit: BoxFit.cover,
),
),
child: Padding(
padding: EdgeInsets.all(AppDimens.EDGE_REGULAR),
child: Column(
children: [
// _customSwitchButton(),
_normalToggleButton(),
],
),
),
),
),
),
);
}
Widget _normalToggleButton () {
return Container(
child: Transform.scale(
scale: 2.0,
child: Switch(
activeColor : Colors.greenAccent,
inactiveThumbColor: Colors.redAccent,
value: _value,
activeThumbImage: AssetImage("images/cnw.png"),
inactiveThumbImage : AssetImage("images/simple_interest.png"),
onChanged: (bool value){
setState(() {
_value = value;
});
},
),
),
);
}
}
You need to rebuild the widget when the state changes. refer the documentation
https://docs.flutter.io/flutter/material/Switch/onChanged.html
I faced the same issue , the problem is your
bool isInstructionView = false;
is in same build method which will get rebuild due to change of switch to render new UI on setState()
Solution is to move it out of function Scope to Class Scope so that your variable do not change on rendering Widget again
To get Switch to work , move the setState(() {}) outside of Switch in a callback function .
// Switch Widget
Switch( value: _toggleState,
onChanged: _attemptChange,
),
//Callback
void _attemptChange(bool newState) {
setState(() {
_toggleState = newState;
newState ? _switchCase = 'ON' : _switchCase = 'OFF';
});
Change SwitchListTile instead of Switch will work.
bool isSwitched = false;
SwitchListTile(
title: Text("title"),
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.symmetric(),
value: isSwitched ,
onChanged: (bool value) {
setState(() {
isSwitched = value;
});
}
)
Use Transform when use Switch will work.
bool isSwitched = false;
Transform.scale(
scale: 1.8,
child: Switch(
onChanged: (value) {
setState(() {
isSwitched = value;
});
},
value: isSwitched,
),
)
I have also got the same problem while I was implementing CupertinoSwitch. I was able to turn it ON but wasn't able to turn it OFF.
According to this example, I tried to put my Switch inside the widget called 'Semantics' and magically it started working.
Below is the code:
body: Column(
children: <Widget>[
SizedBox(height: 50.0,),
Semantics(
container: true,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
CupertinoSwitch(
value: _switchValue,
onChanged: (bool value){
setState(() {
_switchValue = value;
_animating = value;
});
},
),
Text(
"${_switchValue ? "On" : "Off"}",
style: TextStyle(fontSize: 20.0,
fontWeight: FontWeight.bold),
),
],
),
),
SizedBox(
height: 50.0,
),
Visibility(
child: CupertinoActivityIndicator(
animating: _animating,
radius: 30.0,
),
visible: _animating,
),
],
),
Hope it helps.
I'm new to Flutter,
I want to destruct cards created initially and construct them again as per data provided in API call.
Basically when I tap on button in UI, it should call APIs and based on data from API call, if it is different from the data I already have, I want to destruct cards and construct them again.
How I can achieve this?
The cards will auto update their content when you make the call again, it is like refreshing your data.
I have made a simple example with a single card that shows data from this JSON Where I am calling the API first time in initState and then repeating the call each time I press on the FAB.
I am adding the index variable just to show you the updates (updating my single card with the next item in the list)
Also it is worth noting that I am handling the null or empty values poorly for the sake of time.
Also forget about the UI overflow ¯_(ツ)_/¯
class CardListExample extends StatefulWidget {
#override
_CardListExampleState createState() => new _CardListExampleState();
}
class _CardListExampleState extends State<CardListExample> {
Map cardList = {};
int index = 0;
#override
void initState() {
_getRequests();
super.initState();
}
_getRequests() async {
String url = "https://jsonplaceholder.typicode.com/users";
var httpClinet = createHttpClient();
var response = await httpClinet.get(
url,
);
var data = JSON.decode(response.body);
//print (data);
setState(() {
this.cardList = data[index];
this.index++;
});
print(cardList);
print(cardList["name"]);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
floatingActionButton:
new FloatingActionButton(onPressed: () => _getRequests()),
appBar: new AppBar(
title: new Text("Card List Example"),
),
body: this.cardList != {}
? new ListView(children: <Widget>[
new Card(
child: new Column(
children: <Widget>[
new Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
new Text(
cardList["name"] ?? '',
style: Theme.of(context).textTheme.display1,
),
new Text(
this.cardList['email'] ?? '',
maxLines: 50,
),
],
),
new Text(cardList["website"] ?? '')
],
),
),
])
: new Center(child: new CircularProgressIndicator()),
);
}
}
Yes, Answer from Aziza works.
Though I used the code as below :
void main() =>
runApp(new MaterialApp(
onGenerateRoute: (RouteSettings settings) {
switch (settings.name) {
case '/about':
return new FromRightToLeft(
builder: (_) => new _aboutPage.About(),
settings: settings,
);
}
},
home : new HomePage(),
theme: new ThemeData(
fontFamily: 'Poppins',
primarySwatch: Colors.blue,
),
));
class HomePage extends StatefulWidget{
#override
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<HomePage>{
List data;
Future<String> getData() async{
var response = await http.get(
Uri.encodeFull(<SOMEURL>),
headers: {
"Accept" : "application/json"
}
);
this.setState((){
data = JSON.decode(response.body);
});
return "Success";
}
#override
void initState() {
// TODO: implement initState
super.initState();
this.getData();
}
#override
Widget build(BuildContext context){
return new Scaffold(
appBar : new AppBar(
title : new Text("ABC API"),
actions: <Widget>[
new IconButton( // action button
icon: new Icon(Icons.cached),
onPressed: () => getData(),
)],
),
drawer: new Drawer(
child: new ListView(
children: <Widget> [
new Container(
height: 120.0,
child: new DrawerHeader(
padding: new EdgeInsets.all(0.0),
decoration: new BoxDecoration(
color: new Color(0xFFECEFF1),
),
child: new Center(
child: new FlutterLogo(
colors: Colors.blueGrey,
size: 54.0,
),
),
),
),
new ListTile(
leading: new Icon(Icons.chat),
title: new Text('Support'),
onTap: () {
Navigator.pop(context);
Navigator.of(context).pushNamed('/support');
}
),
new ListTile(
leading: new Icon(Icons.info),
title: new Text('About'),
onTap: () {
Navigator.pop(context);
Navigator.of(context).pushNamed('/about');
}
),
new Divider(),
new ListTile(
leading: new Icon(Icons.exit_to_app),
title: new Text('Sign Out'),
onTap: () {
Navigator.pop(context);
}
),
],
)
),
body: this.data != null ?
new ListView.builder(
itemCount: data.length,
itemBuilder: (BuildContext context, int index){
return new Container(
padding: new EdgeInsets.fromLTRB(8.0,5.0,8.0,0.0),
child: new Card(
child: new Padding(
padding: new EdgeInsets.fromLTRB(10.0,12.0,8.0,0.0),
child: new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new ListTile(
enabled: data[index]['active'] == '1' ? true : false,
title: new Text(data[index]['header'],
style:Theme.of(context).textTheme.headline,
),
subtitle: new Text("\n" + data[index]['description']),
),
new ButtonTheme.bar(
child: new ButtonBar(
children: <Widget>[
new FlatButton(
child: new Text(data[index]['action1']),
onPressed: data[index]['active'] == '1' ? _launchURL :null,
),
],
),
),
],
),
),
),
);
},
)
:new Center(child: new CircularProgressIndicator()),
);
}
}
_launchURL() async {
const url = 'http://archive.org';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
class FromRightToLeft<T> extends MaterialPageRoute<T> {
FromRightToLeft({ WidgetBuilder builder, RouteSettings settings })
: super(builder: builder, settings: settings);
#override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child) {
if (settings.isInitialRoute)
return child;
return new SlideTransition(
child: new Container(
decoration: new BoxDecoration(
boxShadow: [
new BoxShadow(
color: Colors.black26,
blurRadius: 25.0,
)
]
),
child: child,
),
position: new Tween(
begin: const Offset(1.0, 0.0),
end: const Offset(0.0, 0.0),
)
.animate(
new CurvedAnimation(
parent: animation,
curve: Curves.fastOutSlowIn,
)
),
);
}
#override Duration get transitionDuration => const Duration(milliseconds: 400);
}
The above code includes Navigation drawer, page navigation animation and also answer to the above question.
I have a FutureBuilder that gets DISTINCT dates from a local sqlite DB, then I take each date and get the messages for those dates to put them in the widget, this works fine, until you want to listen realtime to a stream or poll for new messages which rebuilds the widgets and flickers the page and then scrolls to the beginning each time. I am hoping to find a way to take all the data into some object or other widget and then group by date and order, etc.. This way I can listen to a stream for updated messages, etc..
Any help would be great, here is my code if it helps anyone see what I do, this is after I converted to Streambuilder, but same result.
new StreamBuilder(
initialData: myInitialData,
stream: msgstream,
builder: (BuildContext context, AsyncSnapshot<List<Map>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return new Text('Waiting to start');
case ConnectionState.waiting:
return new Text('');
default:
if (snapshot.hasError) {
return new Text('Error: ${snapshot.error}');
} else {
myInitialData = snapshot.data;
return new RefreshIndicator(
child: new ListView.builder(
itemBuilder: (context, index) {
return new MyChatWidget(
datediv: snapshot.data[index]['msgdate'],
msgkey: snapshot.data[index]['msgkey'],
);
},
//itemBuilder: _itemBuilder,
controller: _scrollController,
reverse: true,
itemCount: snapshot.data.length,
),
onRefresh: _onRefresh
);
}
}
}),
This is the Widget that the StreamBuilder calls:
class MyChatWidget extends StatefulWidget {
MyChatWidget({Key key, this.datediv, this.msgkey}) : super(key: key);
final String datediv;
final String msgkey;
#override
_MyChatWidgetState createState() => new _MyChatWidgetState();
}
class _MyChatWidgetState extends State<MyChatWidget> {
List<Widget> messagelist;
int messagecount = 0;
var jsonCodec = const JsonCodec();
var mydate = '';
var _urlMessages = '';
PageStorageKey _key;
VideoPlayerController vcontroller;
//Future<http.Response> _responseFuture;
Future<List<Map>> _responseFuture;
List messList;
var mybytes;
File myimageview;
Image newimageview;
String imgStr;
String vidStr;
String vidimgstr;
bool submitting = false;
List<Map> myInitialData;
Stream<List<Map>> msgstream;
#override
void initState() {
super.initState();
if (new DateFormat.yMd().format(DateTime.parse(widget.datediv)) ==
new DateFormat.yMd().format(new DateTime.now())) {
mydate = 'Today';
} else {
mydate = new DateFormat.yMMMEd().format(DateTime.parse(widget.datediv));
}
DateChatMessage dcm =
new DateChatMessage(widget.msgkey, widget.datediv.toString());
var json = jsonCodec.encode(dcm);
_urlMessages =
'http://loop-dev.clinicalsoftworks.com/chat/messages/getbydate';
//_responseFuture = http.post(_urlMessages, body: json, headers: getAuthHeader());
_responseFuture =
ChatDB.instance.getMessagesByDate(widget.msgkey, widget.datediv);
msgstream = new Stream.fromFuture(_responseFuture);
//controller = new TabController(length: 4, vsync: this);
//_getMessages();
}
/*#override
void dispose() {
super.dispose();
if (vcontroller != null) {
vcontroller.dispose();
}
}*/
#override
Widget build(BuildContext context) {
_key = new PageStorageKey('${widget.datediv.toString()}');
return new Column(
children: <Widget>[
new Container(
child: new Text(
mydate,
textAlign: TextAlign.left,
style: new TextStyle(
color: Colors.grey,
fontWeight: FontWeight.bold,
),
),
alignment: Alignment.centerLeft,
padding: new EdgeInsets.only(left: 10.0),
),
new Container(
child: new Divider(
height: 5.0,
color: Colors.grey,
),
padding: new EdgeInsets.only(left: 10.0, right: 10.0),
),
/**/
new StreamBuilder(
initialData: myInitialData,
stream: msgstream,
builder: (BuildContext context, AsyncSnapshot<List<Map>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return new Text('Waiting to start');
case ConnectionState.waiting:
return new Text('');
default:
myInitialData = snapshot.data;
List<dynamic> json = snapshot.data;
messagelist = [];
json.forEach((element) {
DateTime submitdate =
DateTime.parse(element['submitdate']).toLocal();
String myvideo = (element['chatvideo']);
String myimage = element['chatimage'];
String myvideoimage = element['chatvideoimage'];
File imgfile;
File vidfile;
File vidimgfile;
bool vidInit = false;
Future<Null> _launched;
String localAssetPath;
String localVideoPath;
String mymessage = element['message'].replaceAll("[\u2018\u2019]", "'");
//print('MYDATE: '+submitdate.toString());
_checkFile(File file) async {
var checkfile = await file.exists();
print('VIDEXISTS: '+checkfile.toString());
}
Future<Null> _launchVideo(String url, bool isLocal) async {
if (await canLaunchVideo(url, isLocal)) {
await launchVideo(url, isLocal);
} else {
throw 'Could not launch $url';
}
}
void _launchLocal() =>
setState(() => _launched = _launchVideo(localVideoPath, true)
);
Widget _showVideo() {
/*return new Flexible(
child: new vplayer.VideoCard(
controller: vcontroller,
title: element['referralname'],
subtitle: 'video',
),
);*/
return new Flexible(
child: new Card(
child: new Column(
children: <Widget>[
new ListTile(subtitle: new Text('Video'), title: new Text(element['referralname']),),
new GestureDetector(
onTap: _launchLocal,
child: new Image.file(
vidimgfile,
width: 150.0,
),
),
],
),
)
);
}
_initVideo() {
setState(() {vidInit = true;});
}
_onError() {
print('VIDEO INIT ERROR');
}
if (myimage != "") {
imgStr = element['chatimage'];
imgfile = new File(imgStr);
}
if (myvideo != "") {
vidStr = element['chatvideo'];
vidimgstr = element['chatvideoimage'];
vidimgfile = new File(vidimgstr);
//vidfile = new File(vidStr);
//_checkFile(vidfile);
//print('vidfile: '+vidfile.path);
localVideoPath = '$vidStr';
//print('LOCALVIDEO: '+localVideoPath);
//vcontroller = new VideoPlayerController('file://$vidStr')..initialize();
}
_showLgPic() {
Route route = new MaterialPageRoute(
settings: new RouteSettings(name: "/ShowPic"),
builder: (BuildContext context) => new ShowPic(
image: imgfile,
),
);
Navigator.of(context).push(route);
}
Widget _showGraphic() {
Widget mywidget;
if (myimage != "") {
mywidget = new GestureDetector(
child: new Image.file(
imgfile,
width: 300.0,
),
onTap: _showLgPic,
);
} else if (myvideo != "") {
mywidget = _showVideo();
} else {
mywidget = new Container();
}
return mywidget;
}
messagelist.add(
new Container(
//width: 300.0,
padding: new EdgeInsets.all(10.0),
child: new Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Container(
padding: new EdgeInsets.only(bottom: 5.0),
child: new Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new CircleAvatar(
child: new Text(
element['sendname'][0],
style: new TextStyle(fontSize: 15.0),
),
radius: 12.0,
),
new Text(' '),
new Text(
element['sendname'],
style: new TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold),
),
new Text(' '),
new Text(
new DateFormat.Hm().format(submitdate),
style: new TextStyle(
color: Colors.grey, fontSize: 12.0),
),
],
),
),
new Row(
children: <Widget>[
new Text(' '),
new Flexible(
child: new Text(mymessage),
)
],
),
new Container(
width: 150.0,
child: new Row(
children: <Widget>[
new Text(' '),
_showGraphic()
/*myimage != ""
? new GestureDetector(
child: new Image.file(
imgfile,
width: 300.0,
),
onTap: _showLgPic,
)
: myvideo != "" ? _showVideo() : new Container(),*/
],
)),
],
),
),
);
});
return new Column(children: messagelist);
}
},
)
],
);
}
}
Thanks for any assistance
which rebuilds the widgets and flickers the page and then scrolls to the beginning each time
To solve problem with scrolling try ScrollController. Create your own, keep it between updates and inject into List you created.
To solve flickering you could use Key for List widgets. Key should be unique identifier of message, e.g. msgkey
This example how to keep scrolloffset works for me
class SomeWidget extends StatefulWidget {
#override
_SomeWidgetState createState() => new _SomeWidgetState();
}
class _SomeWidgetState extends State<SomeWidget> {
ScrollController _scrollController;
int _count;
#override
void initState() {
super.initState();
_count = 10;
_scrollController = new ScrollController();
}
void _add() {
setState(() => _count += 5);
}
#override
Widget build(BuildContext context) {
final _titles = new List<String>.generate(_count, (i) => 'Title ${i}');
return new Scaffold(
appBar: new AppBar(
title: new Text("Demo"),
actions: <Widget>[
new IconButton(icon: new Icon(Icons.add), onPressed: _add)
],
),
body: new ListView.builder(
controller: _scrollController,
itemCount: _titles.length,
itemBuilder: (context, index) => new ListTile(
title: new Text(_titles[index]),
),
),
);
}
}