Flutter setting children dynamically - android

So I want to set the children of my GridView dynamically so I can set it when I want. Currently this is the whole class.
import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/CustomColors.dart';
import 'package:flutter_app/quote/Quote.dart';
import 'package:flutter_app/quote/QuoteView.dart';
import 'package:flutter_app/section/Section.dart';
import 'package:flutter_app/quote/QuoteData.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
static List<QuoteData> data = [];
_readJson() async {
data.clear();
var url = 'https://www.dropbox.com/s/7k280ca5dktlhoo/quotes.json?dl=1';
var httpClient = new HttpClient();
httpClient.getUrl(Uri.parse(url)).then((HttpClientRequest request) {
return request.close();
}).then((HttpClientResponse response) {
response.transform(utf8.decoder).listen((contents) {
List<Map> decoded = JSON.decode(contents);
decoded.forEach((m) {
String url = m["url"];
String title = m["title"];
String sectionString = m["section"];
Section section;
for (Section element in Section.values) {
if (element.toString() == "Section." + sectionString) {
section = element;
}
}
List<Quote> quotes = m["quotes"];
data.add(new QuoteData(url, title, section, quotes));
});
});
});
}
#override
Widget build(BuildContext context) {
_readJson();
return new MaterialApp(
title: 'Quotes',
theme: new ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or press Run > Flutter Hot Reload in IntelliJ). Notice that the
// counter didn't reset back to zero; the application is not restarted.
primarySwatch: CustomColors.black,
),
home: new MyHomePage(title: 'Quotes'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static Section currentSection = Section.movies;
void _onTileClicked(QuoteData quote) {
Navigator.push(context,
new MaterialPageRoute(builder: (context) => new QuoteView(quote)));
}
List<Widget> _getTiles(Section section) {
final List<Widget> tiles = <Widget>[];
for (var i in MyApp.data) {
if (i.section != section) {
continue;
}
tiles.add(new GridTile(
child: new InkResponse(
enableFeedback: true,
child: new Image.network(
i.url,
fit: BoxFit.cover,
),
onTap: () => _onTileClicked(i),
)));
}
return tiles;
}
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
final double itemHeight = (size.height - kToolbarHeight - 24) / 2;
final double itemWidth = size.width / 2;
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return new Scaffold(
appBar: new AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: new Text(currentSection
.toString()
.replaceAll("Section.", "")
.substring(0, 1)
.toUpperCase() +
currentSection.toString().replaceAll("Section.", "").substring(1)),
),
body: new Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: new GridView.count(
crossAxisCount: 2,
childAspectRatio: (itemWidth / itemHeight),
padding: const EdgeInsets.all(4.0),
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
children: _getTiles(currentSection)),
),
);
}
}
So right now on startup, it launches the application but MyApp.data is empty because the json has to be read so the GridView will be empty, when I refresh the application, the GridView won't be empty because MyApp.data won't be empty anymore. I want to be able to set the children after the json gets read, also I need to be able to change it dynamically because I will add a function for switching sections.
The same goes for the title, I also need to be able to change it dynamically when switching sections.

You can create a loading widget and wait for the request to finish when the request is finished hide the loading and show the grid than rebuild the state. but you need to have a statefullWidget not statelessWidget.
You can see how i use it on the code below I added my comments to the code
class _ChildrenPageState extends State<ChildrenPage> {
//declare the _load to true so it will show the loading when the page is loaded
bool _load = true;
ChildrenService _childrenService = new ChildrenService();
List children = [];
//I call the _rebuild function to rebuild the widgets and show the data
void _rebuild() {
setState(() {
});
}
#override
Widget build(BuildContext context) {
//I call the request to get my data when it is finished i put _load to false so the loading will hide and call the _rebuild function to rebuild the widgets and i have put if so when the widget is built it will not rebuild it a second time.
_childrenService.getChildren(children).then((data){
if(data && _load){
_load = false;
_rebuild();
}
});
//the below widget show the loading container if _load is true else it will show the dataTable in your app you should add the grid and you can pass the data that you got from the request
Widget loadingIndicator = _load ? new Container(
color: Colors.grey[300],
width: 70.0,
height: 70.0,
child: new Padding(
padding: const EdgeInsets.all(5.0),
child: new Center(
child: new CircularProgressIndicator()
)
),
) : new JLDataTable(
data: children,
);
return new Scaffold(
drawer: new Drawer(
child: MenuList.menuList,
),
appBar: new AppBar(title: const Text('Data tables')),
body: new ListView(
padding: const EdgeInsets.all(20.0),
children: <Widget>[
new Align(
child: loadingIndicator,
alignment: FractionalOffset.center
)
]
)
);
}
}

Related

Flutter: How to change state of the widget when a certain function has been called?

How it looks like
I've a got bluetooth in my flutter app based on flutter_blue package (^0.8.0). I can connect with my external device and exchange the data. To read data from bluetooth following function is being called when data arrived :
void parseBleMsg(List<int> data) {
print("Data1: $data");
/* Parse the income message */
msgID = data[0];
luxValue = data[1];
print("lux: $luxValue");
print("msgid: $msgID");
}
The parseBleMsg() callback is being set by using specific flutter_blue package methods like setNotifyValue() and .value.listen() :
late BluetoothCharacteristic colsRX;
void setNotifyRX() async {
await colsRX.setNotifyValue(true);
subscription = colsRX.value.listen(
(event) {
parseBleMsg(event);
},
);
}
In one of my app pages I have got a multiple number of buttons which are a custom statefull widgets :
class MeasurementPoint extends StatefulWidget {
final int id;
final double leftPos;
final double topPos;
const MeasurementPoint(
{required this.id, required this.leftPos, required this.topPos});
#override
State<MeasurementPoint> createState() => _MeasurementPointState();
}
class _MeasurementPointState extends State<MeasurementPoint> {
bool pointState = false;
#override
Widget build(BuildContext context) {
return Positioned(
left: widget.leftPos,
top: widget.topPos,
child: ClipOval(
child: Material(
color: pointState ? Colors.green : Styles.primaryColor,
child: InkWell(
onTap: () async {
Bluetooth().bleWrite();
lastClicked = widget.id;
/* TODO : AWAIT FOR BLUETOOTH RESPONSE AND THEN CHANGE STATE */
// setState(() {
// pointState = !pointState;
// });
},
child: const SizedBox(
width: 25, height: 25, child: Icon(Icons.sensors)),
),
),
),
);
}
}
What I want to achieve
As you can see, there is the "TODO" In onTap method. Inside onTap() method I want to send the data through bluetooth to my external device (it works fine) and after that I want to await for the response and then rebuild the widget, to simply change the color of the button as an indicator that the response frame has been received.
The problem I have is that I have no idea, how to await in onTap(), or how in other way rebuilt that widget with new color when I will receive the response from bluetooth.

i want the animated container content change when pressed on it like that

when pressed on quick search the container should expand like this and I don't want to use expandable or any other widget because I want to use the animation of animated container when opened and closed
All credit goes to this post answer: How to create an animated container that hide/show widget in flutter
Here is a Complete Working Code:
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app,
try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the
application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Animated Container Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful,
meaning
// that it has a State object (defined below) that contains fields that
affect
// how it looks.
// This class is the configuration for the state. It holds the values
(in
this
// case the title) provided by the parent (in this case the App widget)
and
// used by the build method of the State. Fields in a Widget subclass
are
// always marked "final".
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
double _height = 50.0;
bool _isExpanded = false;
Future<bool> _showList() async {
await Future.delayed(Duration(milliseconds: 300));
return true;
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as
done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build
methods
// fast, so that you can just rebuild anything that needs updating
rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was
created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: AnimatedContainer(
duration: Duration(milliseconds: 300),
height: _height,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.grey,
),
width: MediaQuery.of(context).size.width - 100,
padding: EdgeInsets.only(left: 15, right: 15),
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Title'),
InkWell(
onTap: () {
if (!_isExpanded) {
setState(() {
_height = 300;
_isExpanded = true;
});
} else {
setState(() {
_height = 50;
_isExpanded = false;
});
}
},
child: Container(
height: 30,
width: 40,
color: Colors.red,
child:
!_isExpanded ? Icon(Icons.add) :
Icon(Icons.remove),
),
),
],
),
),
_isExpanded
? FutureBuilder(
future: _showList(),
/// will wait untill box animation completed
builder: (context, snapshot) {
if (!snapshot.hasData) {
return SizedBox();
}
return ListView.builder(
itemCount: 10,
shrinkWrap: true,
itemBuilder: (context, index) {
return Text('data'); // your custom UI
},
);
})
: SizedBox.shrink(),
],
),
));
}
}
use expandable: flutter pub add expandable,
check the documentation here.

How to store stream data and display new one along with old in a flutter list view?

I'm trying to display a comment stream from Reddit API. I"m using Streambuilder to stream contents as it arrives and displays it as list view thing is I can only view present stream content and this will disappear as new stream contents appear replacing the old ones. If I don't mention item count inside listview.builder prints contents infinitely still new stream appears.
is there a way to display contents along with previous contents in a scrollable fashion and automatically scroll down as a new stream message appears??
Assuming that the comment stream returns individual (and preferably unique) comments one at a time rather than as a list, what you need to do is store the incoming comments in a state object such as a list. When a new comment comes through the stream, you add it to the list and then trigger a widget rebuild.
What you are doing right now is replacing state with each new stream element rather than accumulating them. Using the code you provided, I have edited it to behave as an accumulator instead. Notice the List<Comment> comments = <Comment>[] object added to state. I have also removed the StreamBuilder since that isn't helpful for this use case.
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:draw/draw.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: RedditFlutter(),
debugShowCheckedModeBanner: false,
);
}
}
class RedditFlutter extends StatefulWidget {
RedditFlutter({Key key}) : super(key: key);
#override
_RedditFlutterState createState() => _RedditFlutterState();
}
class _RedditFlutterState extends State<RedditFlutter> {
var comments;
ScrollController _scrollController =
new ScrollController(initialScrollOffset: 50.0);
List<Comment> comments = <Comment>[];
StreamSubscription<Comment>? sub;
var msg = '';
Future<void> redditmain() async {
// Create the `Reddit` instance and authenticated
Reddit reddit = await Reddit.createScriptInstance(
clientId: 'clientid',
clientSecret: 'clientsecret',
userAgent: 'useragent',
username: 'username',
password: 'password', // Fake
);
// Listen to comment stream and accumulate new comments into comments list
sub = reddit.subreddit('cricket').stream.comments().listen((comment) {
if (comment != null) {
// Rebuild from state when a new comment is accumulated
setState(() {
comments.add(comment);
})
}
});
}
#override
void initState() {
// TODO: implement initState
redditmain();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Reddit"),
centerTitle: true,
),
body: Center(
child: Container(
child: ListView.builder(
controller: _scrollController,
itemCount: comments.length,
itemBuilder: (context, index) {
final Comment comment = comments[index];
return Card(
child: ListTile(
leading: Image.asset('assets/criclogo.png'),
title: Text(comment.body),
trailing: Icon(Icons.more_vert),
),
);
},
),
);
),
);
}
#override
void dispose() {
sub?.cancel();
super.dispose();
}
}
Note that I have not tested this code so there may be (trivial) bugs. Still, conceptually, it should be fine.

Flutter setState executing but not rerendering UI when setting parent stateless widget flag

My app has an introductory feature where it simply informs the user on an action to take, the issue is this help action text (Container(...)) does not get removed one the setState() function is called.
Logical overview of process:
-> `User launches app`
|-> `login`
|-> `show main UI (with help action if first time launch)`
|-> first time launch ? show help text : don't show
| User acknowledges help text, set in preferences
Below are some code snippets of the dart fragments
UiHomePage (main UI - this is the parent UI)
class HomePage extends StatefulWidget {
const HomePage({Key key}) : super(key: key);
#override
_HomePage createState() => _HomePage();
}
class _HomePage extends State<HomePage> {
#override
Widget build(BuildContext context) {
Widget pageDashboardUser() {
...
// Notify UiComponentPartnerSelector if we should show help action text based on AppSharedPreferences().isFirstTap()
Widget middleBrowseCard() {
return new FutureBuilder(
builder: (context, snapshot) {
return UiComponentPartnerSelector(
_displayProfiles, snapshot.data);
},
future: AppSharedPreferences().isFirstTap());
}
var search = topSearch();
var selector = middleBrowseCard();
return Stack(
children: [search, selector],
);
return Scaffold(...)
}
This Widget displays a bunch of profiles with a base card, a text overlay, and a hint text component.
The main focus is showHint define in the constructur (true if the app is launched for the first time), showTapTutorial() which either returns the hint component or an empty container and finally the _onTap(Profile) which handles the onclick event of a card.
UiComponentPartnerSelector (sub UI - the help text is shown here
class UiComponentPartnerSelector extends StatefulWidget {
bool showHint;
final List<Profile> items;
UiComponentPartnerSelector(this.items, this.showHint, {Key key})
: super(key: key);
#override
_UiComponentPartnerSelector createState() => _UiComponentPartnerSelector();
}
class _UiComponentPartnerSelector extends State<UiComponentPartnerSelector> {
UiComponentCard _activeCard;
int _tappedImageIndex = 0;
Widget showTapTutorial() {
if (!widget.showHint) {
return Container();
}
return Container(
padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 32),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.6),
borderRadius: BorderRadius.all(Radius.circular(5)),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.touch_app,
color: Colors.black.withOpacity(0.6),
),
Text(
"Touch to view partner profile",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black),
)
],
),
);
}
#override
Widget build(BuildContext context) {
Color _standard = Colors.white;
//
// _cache = widget.items.map((e) => {
// e.imageUri.toString(),
// Image.network(e.imageUri.toString())
// });
Future _onTap(Profile e) async {
if (!widget.showHint) {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => UiViewProfile(e)));
} else {
AppSharedPreferences().setFirstTap(false).then((value) {
setState(() {
widget.showHint = false;
});
});
}
}
UiComponentCard createComponentCard(Profile e) {
...
return UiComponentCard(
onTap: () {
_onTap(e);
},
wImage: Center(
child: Image.network(
e.profileImageLink.toString(),
fit: BoxFit.fill,
),
),
wContent:
// Center(
// child: UiTextLine(text: e.displayName),
// ),
Column(
children: [
topBasicInfo(),
Expanded(child: Container()),
showTapTutorial(),
Expanded(child: Container()),
bottomBio()
],
),
);
}
return Container(
child: Stack(...)
);
Problem:
When _onTap(Profile) is clicked and showHint is true.
What should happen:
What SHOULD happen next is AppSharedPreferences().setFirstTap(false) should set the initial tap flag to false, then when finished setState() including setting showHint to false, then rerendering the UI and removing the hint text container (found in showTapTutorial()).
What happens:
What infact happens is when _onTap() is called, it updates the preferences correctly, setState() is called and showHint == false and !widget.showHint in showTapTutorial() is true returning Container() BUT the UI itself doesn't rerender.
Thus after clicking this "button" for the first time, the UI remains (doesn't change). Clicking a second time executes the Navigator.of(context).push(MaterialPageRoute(builder: (context) => UiViewProfile(e))); part WHILE the action help text (tutorial) is still showing. If I click on the same card again
Am I missing something or doing something wrong?

How do I programmatically add a Text element to my Widget/Class?

I have a widget which calls a function to fetch data from an API; after the fetch function finishes, it calls another function build a table for it's widget. Here's the code:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() => runApp(MeTube());
// class
class MeTube extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return new MeTubeState();
}
}
// state, component
class MeTubeState extends State<MeTube> {
bool _loading = true;
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
// primarySwatch: Colors(212121),
),
home: Scaffold(
appBar: AppBar(
title: Text('MeTube'),
centerTitle: false,
actions: <Widget>[
IconButton(
icon: Icon(Icons.refresh),
onPressed: () {_fetch();}, // call the fetch function (refresh)
)
],
),
body: Center(
child: _loading ? CircularProgressIndicator() : null /* I could load the ListView here
* and use the state to render each row
* but if there are 1,000+ rows, that
* would degrade the performance.
*/
),
)
);
}
// fetch data for the app
_fetch() async {
setState(() {_loading = true;}); // start the progress indicator
final String url = 'api.letsbuildthatapp.com/youtube/home_feed';
final res = await http.get('https://$url');
if (res.statusCode == 200) { // if successful, decode the json
final map = json.decode(res.body);
_build(map['videos'].length, map['videos']); // pass the # videos, and the videos
}
}
// build the data
_build(int rows, data) { /* MAKE EACH ROW */
MeTube().createElement().build( // create a ListView in the Class/Widget
ListView.builder(
itemCount: rows, /* number of rows to render, no need to setState() since this
* function (build) gets called, and the data is passed into it
*/
itemBuilder: (context, index) { // make each column for this class
Column(children: <Widget>[
Text(data[index]['name']), // render some Text and a Divider in each row
Divider()
]);
},
)
);
setState(() {_loading = false;}); // stop the progress indicator
}
}
The current code in the build() function is pretty janky and displays errors. How would I programmatically insert a ListView and Rows into the Widget instead of pushing all the videos to the state, then running code to render a row from all those values in the state?
ListView.builder constructor will create items as they are scrolled onto the screen like on demand. I guess you don't need to worry about performance. Do it like how you commented on the code.

Categories

Resources