Flutter : i want to pass (title,details,content) to details page display it in vertically in top of the details page? - flutter

eg: details about the questions ......................................................when i click to a gridview item i want to pass (title,details,content) to details page display in vertically in top of the details page but when i am pass the data not able to fetch the data in details page i created a constrctor in details page not able to set the data in text and image.
Home Page
----------
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'DetailsPage.dart';
var paddingBottom = 48.0;
class HomePage extends StatelessWidget {
final String apiUrl = "https://www.sofikart.com/MobileApi/banners";
final String apiUrl1 =
"https://wayindia.net/indigo/odia_rashifal/rasifhala.php";
Future<List<dynamic>> fetchUsers() async {
var result = await http.get(Uri.parse(apiUrl1));
return json.decode(result.body)['data'];
}
String id(dynamic user) {
return user['id'];
}
String title(dynamic user) {
return user['title'];
}
String content(dynamic user) {
return user['content'];
}
String eng_title(dynamic user) {
return user['eng_title'];
}
String main_img(dynamic user) {
return user['main_img'];
}
String image_2(dynamic user) {
return user['image_2'];
}
String image_3(dynamic user) {
return user['image_3'];
}
String image_4(dynamic user) {
return user['image_4'];
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ଆଜିର ରାଶିଫଳ'),
centerTitle: true,
),
body: Container(
child: FutureBuilder<List<dynamic>>(
future: fetchUsers(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
print(id(snapshot.data[0]));
return GridView.builder(
itemCount: snapshot.data.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 20,
mainAxisSpacing: 25,
),
padding: EdgeInsets.all(13),
shrinkWrap: true,
itemBuilder: (ctx, index) {
return InkWell(
child: Container(
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.all(Radius.circular(12))),
child: Column(
children: [
Expanded(
flex: 9,
child: ClipRRect(
borderRadius:
BorderRadius.all(Radius.circular(12)),
child: Image.network(
snapshot.data[index]['main_img'],
fit: BoxFit.fill)),
),
Expanded(
flex: 2,
child: Text(
title(snapshot.data[index]),
style: TextStyle(
color: Colors.black, fontSize: 17),
)),
],
),
),
onTap: () {
print("Click event on Container");
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => DetailsPage()), (route) => false);
},
);
},
);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
),
);
}
}
Details Page
------------
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:odia_rasiphala/HomePage.dart';
import 'dart:convert';
class DetailsPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: new Scaffold(
appBar: new AppBar(
title: new Text('ଆଜିର ରାଶିଫଳ'),
leading: new IconButton(
icon: new Icon(Icons.arrow_back_outlined),
onPressed: () => Navigator.pushReplacement(context,
new MaterialPageRoute(builder: (context) => HomePage())),
),
actions: [
IconButton(
onPressed: () {},
icon: Icon(Icons.share),
),
],
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Image.network(
'',
width: 200.0,
height: 200.0,
),
new Center(
child: new Text('',style: TextStyle(
color: Colors.black,fontSize: 17
)),
)
],
),
));
}
}

I am guessing you want to pass "eng_title" and "main_img" to details screen.
To do that first make a constructor in your details pages. Example:
class DetailScreen extends StatelessWidget {
// In the constructor, require a Todo.
const DetailScreen({Key? key, required this.eng_title, required this.main_img}) : super(key: key);
// Declare a field that holds the strings passed to this class.
final String eng_title;
final String main_img;
#override
Widget build(BuildContext context) {
// Use the final parameters to create the UI.
return Scaffold(
appBar: AppBar(
title: Text(eng.title),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(main_img),
),
);
}
}
on your OnTap function, when you click an item on the list, just pass the required parameters like this
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(eng_title: snapshot.data[index]['eng_title'], main_img: snapshot.data[index]['main_img']),
),
);
},
This way you can pass data from onescreen to another. Do not use push and remove until, if you want the user to go back to the list in homepage.
For more info about passing data read the following article by flutter:
https://docs.flutter.dev/cookbook/navigation/passing-data

Related

Flutter: type 'bool' is not a subtype of type 'RxBool' in type cast

I'm Using GetX Package for State Management in Flutter. I'm trying to show data based on whether condition is true or not. But gets this error which says `type 'bool' is not a subtype of type 'RxBool' in type cast'.
Below is my code which I'm trying to show. Thanks for help. :)
HomeScreen
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:github_users/Controllers/status_controller.dart';
import 'package:github_users/Views/show_data.dart';
class HomeScreen extends StatelessWidget {
final statusController = Get.put(StatusController());
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: appBar(),
body: Container(
width: double.maxFinite,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
successButton(context),
SizedBox(height: 20),
faliureButton(context),
],
),
),
);
}
//##############################################
//************** Widget Chunks ***************/
//*************** Appbar ************/
PreferredSizeWidget appBar() {
return AppBar(
backwardsCompatibility: true,
brightness: Brightness.dark,
title: Text(
'Github Users',
),
);
}
//*************** Success Button ************/
Widget successButton(BuildContext context) {
return ElevatedButton(
onPressed: () {
statusController.fetchSuccessData();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ShowData(),
),
);
},
child: Text('Fetch Success Data'),
style: ElevatedButton.styleFrom(
minimumSize: Size(250, 50),
),
);
}
//*************** Faliure Button ************/
Widget faliureButton(BuildContext context) {
return ElevatedButton(
onPressed: () {
statusController.fetchFaliureData();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ShowData(),
),
);
},
child: Text('Fetch Faliure Data'),
style: ElevatedButton.styleFrom(
minimumSize: Size(250, 50),
),
);
}
}
ShowData Screen
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:github_users/Controllers/status_controller.dart';
import 'package:github_users/Models/github_users.dart';
import 'package:github_users/api/users_api.dart';
class ShowData extends StatelessWidget with FaliureStatus {
final statusController02 = Get.put(StatusController());
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[200],
appBar: AppBar(
backwardsCompatibility: true,
brightness: Brightness.dark,
title: Text('Show Data'),
),
body: showBody(context),
);
}
showBody(BuildContext context) {
if (statusController02.isStatusSuccess.value) {
return FutureBuilder<List<GithubUser>>(
future: UserApi.getUsersLocally(context),
builder: (context, snapshot) {
final users = snapshot.data;
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(
child: CircularProgressIndicator(),
);
default:
if (snapshot.hasError) {
return buildUsers(users!);
} else {
return buildUsers(users!);
}
}
},
);
} else {
return showFaliureDialog(context);
}
}
Widget buildUsers(List<GithubUser> users) => ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
final user = users[index];
return Container(
height: 130,
child: Card(
margin: EdgeInsets.symmetric(
horizontal: 15,
vertical: 7,
),
child: Row(
children: [
SizedBox(width: 15),
CircleAvatar(
backgroundImage: NetworkImage(user.avatarUrl),
maxRadius: 30,
),
SizedBox(width: 20),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('User ID: ${user.id}'),
Text('Type: ${user.type}'),
Text('Site Admin: ${user.siteAdmin}'),
Text('Username: ${user.login}'),
],
),
],
),
),
);
},
);
}
mixin FaliureStatus {
showFaliureDialog(BuildContext context) async {
await Future.delayed(const Duration(seconds: 5), () {});
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Error'),
content: Text('No data found! Please check your internet connection'),
actions: [
TextButton(
child: Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
StatusController File
import 'package:get/get.dart';
class StatusController extends GetxController {
RxBool isStatusSuccess = false.obs;
}
Just call isStatusSuccess.value to extract bool value from RxBool
Try isStatusSuccess.isTrue to obtain the bool.
we can use in following way.
if (isStatusSuccess.isTrue)
isStatusSuccess.value = false;
else
isStatusSuccess.value = true;

Add new widget upon clicking floating action button in flutter

I am a beginner in Flutter. I am trying to add a new list item widget to screen when floating action button is pressed. How do I achieve this?
I am trying to create a list of items. When the floating action button is clicked, a dialog box is prompted and user is asked to enter details. I want to add a new list item with these user input details.
This is my input_page.dart file which I am calling in main.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class MedPage extends StatefulWidget {
#override
_MedPageState createState()=> _MedPageState();
}
class _MedPageState extends State<MedPage> {
Future<String>createAlertDialog(BuildContext context) async{
TextEditingController customController= new TextEditingController();
return await showDialog(context: context,builder: (context) {
return AlertDialog(
title: Text("Name of the Pill"),
content: TextField(
controller: customController,
),
actions: <Widget>[
MaterialButton(
elevation: 5.0,
child: Text("OK"),
onPressed: (){
Navigator.of(context).pop(customController.text.toString()); // to go back to screen after submitting
}
)
],
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My med app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget> [
Expanded(
child: ListView(
padding: const EdgeInsets.all(8),
children: <Widget>[
ReusableListItem(Color(0xFFd2fddf),"Name 1"),
ReusableListItem(Colors.orange,"Name 2"),
ReusableListItem(Color(0xFF57a1ab), "Name 3"),
],
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: (){
print("Clicked");
createAlertDialog(context).then((onValue){
print(onValue);
setState(() {
});
});
},
child: Icon(Icons.add),
),
);
}
}
class ReusableListItem extends StatelessWidget {
ReusableListItem(this.colour,this.pill);
Color colour;
String pill;
#override
Widget build(BuildContext context) {
return Container(
height: 50,
margin: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: colour,
borderRadius: BorderRadius.circular(15.0)
),
child: Center(
child: Text(pill)
),
);
}
}
You don't need to change much in your code, maintain a variable that stores the values entered to be able to show them in the list. You should use Listview.builder() in order to dynamically render the items.
Here's your code:
class MedPage extends StatefulWidget {
#override
_MedPageState createState() => _MedPageState();
}
class _MedPageState extends State<MedPage> {
List<String> items = [];
Future<String> createAlertDialog(BuildContext context) async {
TextEditingController customController = new TextEditingController();
return await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("Name of the Pill"),
content: TextField(
controller: customController,
),
actions: <Widget>[
MaterialButton(
elevation: 5.0,
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop(customController.text
.toString()); // to go back to screen after submitting
})
],
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My med app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
return ReusableListItem(Color(0xFFd2fddf), items[index]);
},
itemCount: items.length,
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
print("Clicked");
createAlertDialog(context).then((onValue) {
// print(onValue);
setState(() {
items.add(onValue);
});
});
},
child: Icon(Icons.add),
),
);
}
}
class ReusableListItem extends StatelessWidget {
ReusableListItem(this.colour, this.pill);
final Color colour;
final String pill;
#override
Widget build(BuildContext context) {
return Container(
height: 50,
margin: const EdgeInsets.all(8),
decoration:
BoxDecoration(color: colour, borderRadius: BorderRadius.circular(15.0)),
child: Center(child: Text(pill)),
);
}
}
Firstly you need to use ListView.builder() rather than ListView because you have dynamic content. Also you need to hold your items in a list.
// create a list before
ListView.builder(
itemCount: list.length,
itemBuilder: (BuildContext context, int index) {
return Text(list[index]);
}
)
When you click on FloatingActionButton() you will call AlertDialog() method.
FloatingActionButton(
onPressed: (){
AlertDialog(
content: Form(), // create your form here
actions: [
// add a button here
]
)
})
This method will show a dialog(you will add a form inside of the dialog). When the user completes the form(after clicking the button) you will add a new object to the list and update the state with setState({})
onPressed: (){
setState({
// add new object to the list here
});
Navigator.pop(context); // this will close the dialog
}

Disabling FloatingActionButton after list view and showing a message that the limit is exceeded

How can I disable a button, in this case a FAB(Floating Action Button), and prevent the user adding more items to the list because he is exceeding the limit and showing a message? I'm using a FutureBuilder and a ListView.builder, after the user adds 3 item to the list, I want to disable the FAB and prevent the user to add more items to the list and showing some sort of notification/message/floating over button message to the user that he is exceeding the limit of 3 items per list. Here is the code:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'screens/add_items_screen.dart';
import 'components/items_list.dart';
class ItemScreen extends StatelessWidget {
static const String id = 'item_screen';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
iconTheme: IconThemeData(
color: Colors.grey[600],
),
),
/// I want to disable this button after the limit of 3 items in the list view
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.grey,
child: Icon(Icons.add),
onPressed: () {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (context) => SingleChildScrollView(
child: Container(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom),
child: AddItemScreen(),
)));
},
),
body: SafeArea(
child: SingleChildScrollView(
child: Container(
padding: EdgeInsets.all(20.0),
color: Colors.grey[100],
child: Container(
height: 800,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Item List Display',
style: TextStyle(
fontSize: 22.0,
fontWeight: FontWeight.w700,
),
),
SizedBox(
height: 20.0,
),
Expanded(
child: Column(
children: [
/// Here is where the items are rendered as a list
Expanded(child: ItemList()),
],
),
),
],
),
),
),
),
),
);
}
}
The Item list component:
import 'package:flutter/material.dart';
import 'common/api/api_caller.dart';
import 'utilities/item_api_helper.dart';
import 'models/item.dart';
import 'stores/item_store.dart';
import 'dart:async';
import 'package:provider/provider.dart';
class ItemList extends StatefulWidget {
#override
_ItemList createState() => _ItemList();
}
class _ItemList extends State<ItemList> {
Future<HTTPResponse<List<ItemData>>> _getItemList() async {
var _itemData = await APICaller.instance.getItems();
var provider = Provider.of<ItemDatStore>(context, listen: false);
provider.setItemList(_itemData.data, notify: false);
return _itemData;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: FutureBuilder<HTTPResponse<List<ItemData>>>(
future: _getItemList(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Consumer<ItemDataStore>(
builder: (context, itemData, child) {
return ListView.builder(
itemCount: itemData.itemList.length,
itemBuilder: (context, index) {
ItemData items =
itemData.getItemByIndex(index);
return Card(
child: Container(
padding: EdgeInsets.all(10.0),
child: Text('items.title'),
),
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Container();
},
),
),
);
}
}
I've tried using an if statement where I can define if(itemData.itemList.length <3) it should return those three items, else {Text('Item limit of 3 is exceeded')} but I'm not sure if this is the right way or if I defined it right since I put it in the Item List component and I need to put it in the Item Screen. Thanks in advance for you help!
You can wrap your Floating action button with Visibility it hides and not woking anymore :)
Visibility(
visible: items.length > 3,
child : FAB here,
),
You can disable the FAB like this
onPressed: items.length < 3? addItemToList : null;
and addItemToList is
void addItemToList(){
// Do Something here
}

Flutter - Returning to previous page from AppBar is not refreshing the page, with Navigator.pop(context)

I was trying to get the list page refreshed if a method was run on another page. I do pass the context using the push navigation.
I tried to follow these 3 answers Answer 1 Answer 2 and Answer 3 and I am not able to manage the states here.
This is the first list page which needs to be refreshed. It calls a class
class _PageLocalState extends State<PageLocal> {
#override
Widget build(BuildContext context) {
return Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: SafeArea(
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: widget.allLocal.length,
//padding: const EdgeInsets.only(top: 10.0),
itemBuilder: (context, index) {
return LocalCard(widget.allLocal[index]);
},
)),
)
],
),
);
}
}
The next class:
class LocalCardState extends State<LocalCard> {
FavData localdet;
LocalCardState(this.localdet);
ListTile makeListTile() => ListTile(
contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
title: Text(
localdet.name,
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(localdet.loc),
trailing: Icon(Icons.keyboard_arrow_right, size: 30.0),
onTap: () => navigateToDetail(localdet),
);
Widget get localCard {
return new Card(
elevation: 4.0,
margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
child: Container(
child: makeListTile(),
));
}
#override
Widget build(BuildContext context) {
return new Container(
child: localCard,
);
}
navigateToDetail(FavData localdet) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FavouriteDetailPage(
mndet: localdet,
)));
setState(() {});
}
}
Now this is routing to the final detail page:
class _FavouriteDetailPageState extends State<FavouriteDetailPage> {
bool isFav = false;
FavData mndet;
_FavouriteDetailPageState(this.mndet);
// reference to our single class that manages the database
final dbHelper = DatabaseHelper.instance;
#override
Widget build(BuildContext context) {
Widget heading = new Container(...);
Widget middleSection = new Expanded(...);
Widget bottomBanner = new Container(...);
Widget body = new Column(...);
final makeBottom = Container(
height: 55.0,
child: BottomAppBar(
color: Color.fromRGBO(36, 36, 36, 1.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new FavIconWidget(mndet),
],
),
),
);
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('The Details'),
backgroundColor: Color.fromRGBO(36, 36, 36, 1.0),
),
body: Container(
child: Card(
elevation: 5.0,
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.white70, width: 1),
borderRadius: BorderRadius.circular(10),
),
margin: EdgeInsets.all(20.0),
child: Padding(
padding: new EdgeInsets.symmetric(vertical: 16.0, horizontal: 16.0),
child: body,
),
),
),
bottomNavigationBar: makeBottom,
);
}
void share(BuildContext context, FavData mndet) {
final RenderBox box = context.findRenderObject();
final String shareText = "${mndet.name} - ${mndet.desc}";
Share.share(shareText,
subject: mndet.loc,
sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
}
}
class FavIconWidget extends StatefulWidget {
final FavData mnforIcon;
FavIconWidget(this.mnforIcon);
#override
_FavIconWidgetState createState() => _FavIconWidgetState();
}
class _FavIconWidgetState extends State<FavIconWidget> {
final dbHelper = DatabaseHelper.instance;
Future<bool> get isFav async {
final rowsPresent = await dbHelper.queryForFav(widget.mnforIcon.id);
if (rowsPresent > 0) {
print('Card Loaded - Its Favourite already');
return false;
} else {
print('Card Loaded - It is not favourite yet');
return true;
}
}
void _insert() async {...}
void _delete() async {...}
#override
Widget build(BuildContext context) {
return FutureBuilder<bool>(
future: isFav,
initialData:
false, // you can define an initial value while the db returns the real value
builder: (context, snapshot) {
if (snapshot.hasError)
return const Icon(Icons.error,
color: Colors.red); //just in case the db return an error
if (snapshot.hasData)
return IconButton(
icon: snapshot.data
? const Icon(Icons.favorite_border, color: Colors.white)
: Icon(Icons.favorite, color: Colors.red),
onPressed: () => setState(() {
if (!snapshot.data) {
print('Its favourite so deleting it.');
_delete();
} else {
print('Wasnt fav in the first place so inserting.');
_insert();
}
}));
return CircularProgressIndicator(); //if there is no initial value and the future is not yet complete
});
}
}
I am sure this is just some silly coding I have done but just not able to find out. Where.
I tried adding Navigator.pop(context); in different sections of the detail page and it fails.
Currently, I have to navigate back to the Favourites list page and then HomePage and then back to Favourites ListPage to refresh the list.
try this.. Anywhere you are using Navigator.pop or Navigator.push .. Instead of this use this:
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (BuildContext context) => Password())
);
//instead of Password use the name of the page(the second page you want to go to)

Flutter Cannot show List item in Drawar

I am new to flutter.
I am trying to create list view dynamically using server response JSON data using futureBuilder. The code writen by me while wathing YouTube videos, but I can't understand what is the mistake.
//It looks like your post is mostly code; please add some more details.//
main.dart
import 'package:flutter/material.dart';
import 'home.dart';
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: home(),
));
}
home.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
class home extends StatefulWidget {
home({Key key}):super();
#override
homepage createState() =>new homepage();
}
class homepage extends State<home>{
Color theme = Colors.lightBlue;
Color theme_text = Colors.white;
Future<List<category>> _getCategory() async {
var data = await http
.get("https://next.json-generator.com/api/json/get/VJ6EHYFO_");
debugPrint(data.body);
var jsondata = json.decode(data.body);
List<category> list = [];
for (var u in jsondata) {
category c = category(u['name'], u['id']);
list.add(c);
}
return list;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: theme,
title: Text('SIMS Home Page'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.shopping_cart),
onPressed: () => debugPrint("search pressed"),
)
],
),
drawer: Drawer(
child: ListView(
children: <Widget>[
DrawerHeader(
child: Text(
"Not Signed",
textAlign: TextAlign.center,
style: TextStyle(color: theme_text, fontSize: 20),
),
decoration: BoxDecoration(
color: theme,
),
),
FutureBuilder(
future: _getCategory(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Container(
child: Center(
child: Text("Loading..."),
),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(title: Text(snapshot.data[index]),);
});
}
},
),
],
),
),
);
}
class category {
final name;
final id;
category(this.name, this.id);
}
You have to use shrinkwrap property of listView.builder to get it work. it will allow listview to grow only that much which is require.
Moreover, in text view you are assigning items directly you have to access name and id individually as shown in below code.
Container(
height: 150,
child: DrawerHeader(
child: Text(
"Not Signed",
textAlign: TextAlign.center,
style: TextStyle(color: theme_text, fontSize: 20),
),
decoration: BoxDecoration(
color: theme,
),
),
),
FutureBuilder(
future: _getCategory(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Container(
child: Center(
child: Text("Loading..."),
),
);
} else {
return Container(
height: MediaQuery.of(context).size.height - 150,
child: ListView.builder(
shrinkWrap: true, //added line
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(snapshot.data[index]
.toString()), //accessing name from json
);
}),
);
}
},
),