Creating a new widget on User Click(Flat Button) - flutter

I have a Post class that creates a Post model. And I want to create this model every time a user clicks the flat button. What's the best way to go about this using the onPressed function?
It's going to be a post that holds the text the user adds to the text field and when they submit it will show on a new post.

u can try use listview.builder, this the simple example how to use it. i just edit default code when we created new project.
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: ListView.builder(
itemCount: _counter,
reverse: true,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(10.0),
child: Container(
color: Colors.red,
child: Center(child: Text('data $index')),
),
);
},
)
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);

Basically you want to add items to a list, and then render the contents of that list.
List<String> messages = [];
...
onPressed: ()=> setState(()=>messages.add("SomeText"))
Then render the list:
//Can use the map() api, to convert the list of Strings into a list of widgets:
List<Widget> children = messages.map((m) => Text(m));
return ListView(children: children);
//Or, use ListView.builder() to create the widgets on demand:
return ListView.builder(
itemBuilder: (context, index)=>Text(messages[index]),
itemCount: messages.length
)
The builder method is better optimized for large lists.

here is simple demo
List<String> posts = [];
#override
Widget build(BuildContext context) {
return Scaffold(body: Column(
children: <Widget>[
ListView.builder(
itemCount: posts.length,
itemBuilder: (BuildContext ctxt, int index) {
return new Text(posts[index]);//use any widget
}
),
FloatingActionButton(
backgroundColor: Colors.white,
child: Icon(
Icons.close,
color: Colors.red,
),
onPressed: () {
setState(() {
posts.add(newpost);//add what you want
});
},
),
]),
);
}
i hope it helps..

Related

How can I make a scaffold scrollable in Flutter?

I've tried a lot to make a list scrollable, but it never worked.
Everytime I wrapped it in a SingleChildScrollView my list just disappeared.
Can someone help pls
Here is my code:
return Scaffold(
body:
SingleChildScrollView(
child: ListView.builder(
itemCount: subjects.length,
itemBuilder: (context, i) {
return singleSubject(
subjects[i],
() => deleteItem(i),
);
},
),
),
floatingActionButton: FloatingActionButton(
backgroundColor: const Color(0xFF383838),
onPressed: newSubject,
child: const Icon(Icons.add),
),
backgroundColor: const Color(0xFFB94844),
);
}
}
You dont need to use SingleChildScrollView while ListView is the only child on body.
Do
body: ListView.builder(
Find more about widgets/scrolling

Removing button and load data

Hey guys I need help with removing this button and load data from json file without need to click on that button
Here's code
List _items = [];
// Fetch content from the json file
#override
Widget build(BuildContext context) {
Future readJson() async {
final String response =
await rootBundle.loadString('assets/aaaa.json');
final data = await json.decode(response);
setState(() {
_items = data['first'];
});
}
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(25),
child: Column(
children: [
ElevatedButton(
child: const Text('Load Data'),
onPressed: readJson,
),
// Display the data loaded from sample.json
_items.isNotEmpty
? Expanded(
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (context, index) {
return Card(
margin: const EdgeInsets.all(10),
child: ListTile(
leading: Text(_items[index]["aaaaa"]),
title: Text(_items[index]["aaaaa"]),
subtitle: Text(_items[index]["aaaaaa"]),
),
);
},
),
)
: Container()
],
),
),
);
}
You should check out Future Builder. There are some good examples on that page of how to use the widget, including how to show different widgets depending on if the data was loaded, is in the process of loading, or there was an error. readJson would be the future in your case.
Call initState() before build function
#overrride
initState() {
readJson();
super.initState();
}
Calling the readJson() function just before returning Scaffold will do what you want.
Widget build(BuildContext context) {
//load the json content
readJson();
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(25),
child: Column(
children: [
// Display the data loaded from sample.json
_items.isNotEmpty
? Expanded(
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (context, index) {
return Card(
margin: const EdgeInsets.all(10),
child: ListTile(
leading: Text(_items[index]["aaaaa"]),
title: Text(_items[index]["aaaaa"]),
subtitle: Text(_items[index]["aaaaaa"]),
),
);
},
),
)
: Container()
],
),
),
);}

Flutter: how to delete item in ListTile

If i use Navigator, class is finished by itself.
I just want to delete the list.
code image is here
body: Container(
child: Center(
child: ListView.builder(
itemCount: 100,
itemBuilder: (context, index) {
return ListTile(
title: launchButton('linkbutton','https://stackoverflow.com/questions/ask'),
trailing: OutlinedButton(
onPressed: () {
},
child: Icon(Icons.delete_forever),
Add an itemCount to your ListView.Builder.
Then if you want to delete the item at the given index, you can create a function and put it in your onpressed
deleteItem(int index){
yourList.removeWhere(index);
}

How to clear objects in a listviewbuilder in flutter?

How to control listviewbuilder from outside the listview in flutter?
In a textfield I can use a controller like so: controller: Textcontroller. Can I do something similar in listviewbuilder to clear all the objects in it?
So to be exact. My code looks something like this
Expanded(
child: new ListView.builder(
itemCount: List.length,
itemBuilder: (context,index){
return new Card(
//all stuff with data
),
),
);
},
....
How would I do so that when called from another function it removes all the items in the listview?
You need a Store class that holds this list along with list manipulation methods, then you can use provider for example to access that class and render that list.
You can define a variable in the state of your widget:
var _clear = false;
When this variable is true, the list will be cleared and when it's false, the list will be displayed. You can use setState to toggle this variable. Setting the itemCount of the ListView.builder to 0 clears the list.
Full code:
var _clear = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(30.0),
child: FlatButton(
child: Text('clear'),
color: Colors.pinkAccent,
onPressed: () {
setState(() {
_clear = true;
});
},
),
),
FlatButton(
child: Text('add'),
color: Colors.greenAccent,
onPressed: () {
setState(() {
_clear = false;
});
},
),
Expanded(
child: ListView.builder(
controller: _scrollController,
itemCount: _clear ? 0 : 100,
itemBuilder: (context, index) {
return Container(
height: 300,
child: Card(
child: Center(
child: Text('$index'),
),
),
);
},
),
),
],
),
);
}

Wrapping Gesture detector around a card

Right now i have a button on the body of the page but cannot implement this button (that routes to a different page) to just encapsulate just the card that is
child: new Text(data["data"][index]["title"]),
it is inside of an itemBuilder so i thought i had to do a GestureDetector. Ive tried to put that child into the GestureDetector method but cannot get it to work unless its the whole body.
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Listviews"),
),
body: new GestureDetector(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => StandardsControlPage()),
);
},
child: Container(
padding: EdgeInsets.all(16.0),
child: new ListView.builder(
itemCount: data == null ? 0 : data["data"].length,
itemBuilder: (BuildContext context, int index) {
return new Card(
child: new Text(data["data"][index]["title"]),
);},
),
),
),
);
}}
This example wont work if i have multiple buttons to press with different routes, and was wondering If there is anyway to implement a button with that route to just that child, how would i do it?
return new Scaffold(
appBar: new AppBar(
title: new Text("Listviews"),
),
body: Container(
padding: EdgeInsets.all(16.0),
child: new ListView.builder(
itemCount: data == null ? 0 : data["data"].length,
itemBuilder: (BuildContext context, int index) {
return new GestureDetector(
child: new Card(
child: new Text(data["data"][index]["title"]),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StandardsControlPage()),
);
},
);
},
),
));
I think this will work.