convert data from a csv to a dynamic List (Flutter) - csv

I create an app that loads the CSV file and displays it as a list view, I have used the following example. https://gist.github.com/Rahiche/9b4b2d3b5c24dddbbe662b58c5a2dcd2
The problem is that my List, don't generate rows
I/flutter ( 2158): [[M01, Plastics, 50, NA
I/flutter ( 2158): M02, Plastics, 85, NA
I/flutter ( 2158): M03, Wood, 50, NA
I/flutter ( 2158): M04, Wood, 15, 3
I/flutter ( 2158): M05, Plastics, 50, NA]]
Here is my code
class TableLayout extends StatefulWidget {
#override
_TableLayoutState createState() => _TableLayoutState();
}
class _TableLayoutState extends State<TableLayout> {
List<List<dynamic>> data = [];
loadAsset() async {
final myData = await rootBundle.loadString("assets/ford.csv");
List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);
print(csvTable);
data = csvTable;
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh),
onPressed: () async {
await loadAsset();
//print(data);
}),
appBar: AppBar(
title: Text("Table Layout and CSV"),
),
body: SingleChildScrollView(
child: Table(
columnWidths: {
0: FixedColumnWidth(100.0),
1: FixedColumnWidth(200.0),
},
border: TableBorder.all(width: 1.0),
children: data.map((item) {
return TableRow(
children: item.map((row) {
return Container(
color:
row.toString().contains("NA") ? Colors.red : Colors.green,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
row.toString(),
style: TextStyle(fontSize: 20.0),
),
),
);
}).toList());
}).toList(),
),
),
);
}
}
and my ford.csv
M01,Plastics,50,NA
M02,Plastics,85,NA
M03,Wood,50,NA
M04,Wood,15,3
M05,Plastics,50,NA
---
i tried the hints from https://pub.dev/packages/csv#-readme-tab- and from
Not viewing Table Layout from a csv in flutter and I have read several csv files
but every time i have the same issues.
what am I doing wrong??
Please help a new flutter developer. ;)

You can copy paste run full code below
I add setState in function loadAsset()
I did not encounter column width issue, if you still have this issue, please try to add column 2 , 3 or shrink width of FixedColumnWidth
columnWidths: {
0: FixedColumnWidth(100.0),
1: FixedColumnWidth(100.0),
2: FixedColumnWidth(50.0),
},
code snippet
loadAsset() async {
final myData = await rootBundle.loadString("assets/ford.csv");
List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);
print(csvTable);
data = csvTable;
setState(() {
});
}
working demo
animated gif did not show correct green color,
so I paste final result in second picture
full code
import 'package:flutter/material.dart';
import 'package:csv/csv.dart';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// 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: TableLayout(),
);
}
}
class TableLayout extends StatefulWidget {
#override
_TableLayoutState createState() => _TableLayoutState();
}
class _TableLayoutState extends State<TableLayout> {
List<List<dynamic>> data = [];
loadAsset() async {
final myData = await rootBundle.loadString("assets/ford.csv");
List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);
print(csvTable);
data = csvTable;
setState(() {
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh),
onPressed: () async {
await loadAsset();
//print(data);
}),
appBar: AppBar(
title: Text("Table Layout and CSV"),
),
body: SingleChildScrollView(
child: Table(
columnWidths: {
0: FixedColumnWidth(100.0),
1: FixedColumnWidth(200.0),
},
border: TableBorder.all(width: 1.0),
children: data.map((item) {
return TableRow(
children: item.map((row) {
return Container(
color:
row.toString().contains("NA") ? Colors.red : Colors.green,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
row.toString(),
style: TextStyle(fontSize: 20.0),
),
),
);
}).toList());
}).toList(),
),
),
);
}
}

It's because of different EOL (END OF LINE) characters that are used to terminate a line in file. i.e Some program use '\r\n' while other '\n'.
So to solve the issue you have to consider that. i.e I am using csv package on window os and while reading from a csv file, you should specify eol argument to convert method of the CsvToListConverter().
return CsvToListConverter().convert(csv.data, eol: '\n');

The fast_csv parser is for parsing CSV data.
It is 2.9-4.7 times faster than the csv parser.
If you need to parse large amounts of data, then it will be more efficient.
Line endings are \n, \r\n or \r (no need to configure).
import 'package:fast_csv/fast_csv.dart' as _fast_csv;
void main(List<String> args) {
final res = _fast_csv.parse(_csv);
print(res);
}
final _csv = '''
M01,Plastics,50,NA
M02,Plastics,85,NA
M03,Wood,50,NA
M04,Wood,15,3
M05,Plastics,50,NA
''';
Output:
[[M01, Plastics, 50, NA], [M02, Plastics, 85, NA], [M03, Wood, 50, NA], [M04, Wood, 15, 3], [M05, Plastics, 50, NA]]

Related

API give data NULL in first Load

I get the data from API and when API calls on the first load of the screen so API gets the data but in response, the data shows the null value, and when I click on hot reload it response shows data from API.
I don't know what happens with API or response.
Please someone help me to understand what happened with the response I also used await but nothing happens.
Here is my code:-
import 'package:flutter/material.dart';
import 'package:mindmatch/utils/widget_functions.dart';
import 'package:mindmatch/screens/Favorites.dart';
import 'package:mindmatch/screens/Editprofile.dart';
import 'package:getwidget/getwidget.dart';
import 'package:mindmatch/screens/Sidebar.dart';
import 'package:mindmatch/screens/Footer.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:mindmatch/utils/Auth.dart';
class Profile extends StatefulWidget {
var usrid;
Profile({Key? key, #required this.usrid}) : super(key: key);
#override
_Profile createState() => _Profile();
}
class _Profile extends State<Profile>{
//SingingCharacter? _character = SingingCharacter.male;
var url;
var data;
final body = null;
#override
Widget build(BuildContext context){
var UsrID = widget.usrid;
final Size size = MediaQuery.of(context).size;
final ThemeData themeData = Theme.of(context);
final double padding = 25;
final sidePadding = EdgeInsets.symmetric(horizontal: padding);
var url = Uri.https('www.******.net', '/mm_api/index.php',{'act':'profile','UsrID': UsrID});
print(url);
// print(getData());
Future getData() async{
final res = await http.get(
url,
headers: {'Content-Type': 'application/json'},
);
//var res = await http.get(Uri.parse('www.*******.net/mm_api/index.php?act=profile&UsrID=${UsrID}'));
print(res);
//data = json.decode(res.body);
data = jsonDecode(res.body);
print(data);
//setState(() {});
//print(res.body);
}
#override
void initState() async{
super.initState();
getData();
// print (await getData());
}
print(data);
//print(getData());
//return SafeArea(
return Scaffold(
appBar: AppBar(
titleSpacing: 3,
backgroundColor: Colors.white,
elevation: 0,
title: Text('My Profile', style: TextStyle(color: Colors.black, fontSize: 15,),),
leading: Builder(
builder: (BuildContext context) {
return Padding(padding: EdgeInsets.fromLTRB(15, 0, 0, 0),
child: IconButton(
icon: SvgPicture.asset(
width: 30,
'assets/images/Menu.svg',
height: 30,
),
onPressed: () { Scaffold.of(context).openDrawer(); },
tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
),
);
},
),
actions: <Widget>[
Padding(
padding: sidePadding,
child: Row(
children: [
//Icon(Icons.search, color: Colors.black,),
SvgPicture.asset(
width: 30,
'assets/images/search.svg',
height: 30,
),
],
)
)
],
),
backgroundColor: Color(0xff8f9df2),
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
//colors: const [Color.fromRGBO(132,105,211,1), Color.fromRGBO(93,181,233,1), Color.fromRGBO(86,129,233,1)],
colors: [Colors.white, Colors.white]
),
),
width: size.width,
height: size.height,
child: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//addVerticalSpace(30),
data != null?Expanded(
child: Padding(
padding: sidePadding,
child: ListView(
physics: BouncingScrollPhysics(),
children: [
Text('${data[0]['name']}')
],
),
)
): const Center(
child: CircularProgressIndicator(),
)
],
),
],
)
),
drawer: Sidebar(),
persistentFooterButtons: [
Footer(usrid:UsrID),
],
);
//);
}
}
When first load screen it shows me a null value:- Here I Print data form response but it shows me a null value
And when I hot reload the screen it shows me the response value:- It shows the value and I comment any print value or hot reload the screen
Data from API:-
[{"id":"1","name":"anni","fulname":"anni ann","mobile":"+15214639870","email":"anni#gmail.com","about":"sdhbsdbcshcbsdhcbsbchsdb\ncbhbchsc","lookfor":"Relationship, Networking","education":"gcnd,2018","work":"dhfjsk,fjskk","politics":"Liberal, Apolitical","religion":"Protestant, Anglican, Hindu","children":"Have + don't want more, Have and want more","interests":"Treking, Sports, Cooking","distance":" 17 ","age":" 20, 60 "}]
when I test API on the browser it shows correct data but does not show in response
WHY?
Please help me to understand this.
I don't know whats going on with the response
It also looks like you are calling initState in your build method. You have to move it out of build method as it is a separate override method.
You have to call setstate after catching data from api
add this line in your getdata() at the end setstate()
setstate() is used to hot reload programatically so in other words when your app update it's state or any information which is used by your app you have to call setstate() function for reflate on your app's ui.
setstate() function call build method one time again and draw whole tree again.
if you have not use setstate then i suggest some code below do this.
final res = await http.get(
url,
headers: {'Content-Type': 'application/json'},
);
//var res = await http.get(Uri.parse('www.*******.net/mm_api/index.php?act=profile&UsrID=${UsrID}'));
print(res);
//data = json.decode(res.body);
dynamic data = jsonDecode(res.body);
print(data);
return data;
//setState(() {});
//print(res.body);
}
//then edit your future builder
FutureBuilder(builder: (context, snapshot) {
if(snapshot.connectionState==ConnectionState.waiting){
//return loader
}else {
if(snapshot.hasData==true){
//update your ui
}else{
//data is null
}
}
}```

parsing JSON file in flutter

I am parsing this type of JSON file in flutter but I am getting error.
initially, I am able to print the whole data in the console but when I want only the name it gives me an error.
bellow in the image for JSON file.
this the code that I wrote for parsing which gives me 1st value of name as "Abul-Abbas" then it throws an error.
import 'package:flutter/material.dart';
import 'package:flutter_appnew/Constants.dart';
import 'package:flutter_appnew/network.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
const URL ='https://xxxx-api.someapp.com/xxx';
class TabData extends StatefulWidget {
#override
_TabDataState createState() => _TabDataState();
}
class _TabDataState extends State<TabData> {
List image = [];
List Name = [];
#override
void initState() {
super.initState();
this.fetchUser();
}
fetchUser() async{
var response = await http.get(URL);
print(response.statusCode);
if(response.statusCode == 200){
var items = json.decode(response.body)[0]['name'];
print(items);
setState(() {
Name = items;
});
}
else{
setState(() {
Name = [];
});
}
}
#override
Widget build(BuildContext context) {
return ListView.separated(
itemCount: Name.length,
itemBuilder: (BuildContext context, int index){
return getCard(context, index);
},
separatorBuilder: (context, index) => Divider(thickness: 2,),
);
}
Widget getCard(BuildContext context, int index){
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
title: Row(
children: [
Container(
height: 60,
width: 60,
decoration: BoxDecoration(
color: Colors.purple,
borderRadius: BorderRadius.circular(30),
image: DecorationImage(
image: NetworkImage('${image[index]}'),
fit: BoxFit.cover,
),
),
),
SizedBox(width: 20,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('${Name[index]}', style: kListTileTextNameStyle,),
],
),
],
),
),
),
);
}
}
and the same is happening with the image I am not able to show it.
please help this is my first time with JSON file parsing.
I can advice you to try to avoid the dynamic type. Your
var items = json.decode(response.body)[0]['name'];
assigns the items to be the type String and the value is "Abul-Abbas". After that you assign Name which is a List to items which is of type String.
What you actually want to do is to add all names to the list (I guess).
So you should do:
response.body.forEach((element) {
Name.add(element["name"]);
});
I also recommend Renaming Name to names.
If you just wanted the first value of your response, then Name should be of type String.

local JSON results are not shwoing - Flutter

I have a local JSON file that contains a list of words and I want to display the words in a list using flutter/Dart, for some reason the results are not displayed. All I get is a blank page along with this exception:
The following NoSuchMethodError was thrown building FutureBuilder(dirty, state:
I/flutter (25570): _FutureBuilderState#b10bc):
This is the code I am working with:
class _ListContentState extends State<ListContent> {
List<WordsDictionary> _words = List<WordsDictionary>();
Future<List<WordsDictionary>> _getWords() async{
var dictionaryData = await
DefaultAssetBundle.of(context).loadString('assets/json/dictionary.json');
var words = List<WordsDictionary>();
if(dictionaryData != null){
var jsonData = json.decode(dictionaryData);
for(var word in jsonData){
words.add(WordsDictionary.fromJson(word));
}
}else {
print('fail');
}
return words;
}
#override
void initState(){
_getWords().then((value) {
setState(() {
_words.addAll(value);
});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemBuilder: (context, index) {
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(top: 6.0, bottom: 6.0, left: 8.0, right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(_words[index].wordEnglish,),
Spacer(),
Text(_words[index].wordGerman,),
],
),
),
);
},
itemCount: _words.length,
);
}
}
WordDictionary.dart :
class WordsDictionary {
int wordId;
String wordEnglish;
String wordGerman;
WordsDictionary(
this.wordId,
this.wordEnglish,
this.wordGerman
);
WordsDictionary.fromJson(Map<String, dynamic> json){
wordId = json['wordId'];
wordEnglish = json['englishWord'];
wordGerman = json['germanWord'];
}
}
Please wrap your list view with future builder
I slightly change your WordsDictionary class
example json
[
{
"wordId" : "1",
"wordEnglish" : "abc",
"wordGerman" : "def"
},
{
"wordId" : "2",
"wordEnglish" : "123",
"wordGerman" : "456"
}
]
the following is full working code
import 'package:flutter/material.dart';
import 'dart:convert';
void main() => runApp(MyApp());
// To parse this JSON data, do
//
// final wordsDictionary = wordsDictionaryFromJson(jsonString);
List<WordsDictionary> wordsDictionaryFromJson(String str) =>
List<WordsDictionary>.from(
json.decode(str).map((x) => WordsDictionary.fromJson(x)));
String wordsDictionaryToJson(List<WordsDictionary> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class WordsDictionary {
String wordId;
String wordEnglish;
String wordGerman;
WordsDictionary({
this.wordId,
this.wordEnglish,
this.wordGerman,
});
factory WordsDictionary.fromJson(Map<String, dynamic> json) =>
WordsDictionary(
wordId: json["wordId"],
wordEnglish: json["wordEnglish"],
wordGerman: json["wordGerman"],
);
Map<String, dynamic> toJson() => {
"wordId": wordId,
"wordEnglish": wordEnglish,
"wordGerman": wordGerman,
};
}
class MyApp extends StatelessWidget {
// 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: ListContent(),
);
}
}
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() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#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: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class ListContent extends StatefulWidget {
#override
_ListContentState createState() => _ListContentState();
}
class _ListContentState extends State<ListContent> {
List<WordsDictionary> _words = List<WordsDictionary>();
Future<List<WordsDictionary>> _getWords() async {
var dictionaryData = await DefaultAssetBundle.of(context)
.loadString('assets/json/dictionary.json');
var words = List<WordsDictionary>();
if (dictionaryData != null) {
words = wordsDictionaryFromJson(dictionaryData);
print("words lenght ${words.length}");
} else {
print('fail');
}
return words;
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
builder: (context, AsyncSnapshot<List<WordsDictionary>> wordSnap) {
switch (wordSnap.connectionState) {
case ConnectionState.none:
return new Text('none');
case ConnectionState.waiting:
return new Center(child: new CircularProgressIndicator());
case ConnectionState.active:
return new Text('');
case ConnectionState.done:
if (wordSnap.hasError) {
return new Text(
'${wordSnap.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: wordSnap.data.length,
itemBuilder: (context, index) {
WordsDictionary wordsDictionary = wordSnap.data[index];
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(
top: 6.0, bottom: 6.0, left: 8.0, right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
wordsDictionary.wordEnglish,
),
Spacer(),
Text(
wordsDictionary.wordGerman,
),
],
),
));
});
}
}
},
future: _getWords(),
);
}
}

Flutter doesn't want to import json

I am trying to follow this official tutorial in order to make a web request to an url: https://flutter.io/cookbook/networking/fetch-data/
I have thus added these lines in pubspec.yaml:
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
http: 0.11.3+17
json_annotation: ^0.2.3
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^0.9.0
json_serializable: ^0.5.4
and when compiling, I got this error.
Compiler message: lib/main.dart:53:26: Error: Method not found:
'decode'.
return Post.fromJson(json.decode(response.body));
Any idea what I am doing wrong?
Here is my code:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo2',
theme: new ThemeData(
primarySwatch: Colors.amber,
),
home: new MyHomePage(title: 'Islam Essentiel'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({this.userId, this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
Future<Post> fetchPost() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts/1');
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load post');
}
}
class _MyHomePageState extends State<MyHomePage> {
void _incrementCounter() {
setState(() {
});
}
#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 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(widget.title),
),
body: new Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: new Column(
// Column is also layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug paint" (press "p" in the console where you ran
// "flutter run", or select "Toggle Debug Paint" from the Flutter tool
// window in IntelliJ) to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Card(
child: new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
leading: const Icon(Icons.album),
title: const Text('al-khamis: 30. Muharram 1440'),
subtitle: const Text('20:51 - Icha.'),
),
new ButtonTheme.bar( // make buttons use the appropriate styles for cards
child: new ButtonBar(
children: <Widget>[
new FlatButton(
child: const Text('MECQUE - DIRECTION'),
onPressed: () { /* ... */ },
),
],
),
),
],
),
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: fetchPost,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
);
}
}
You need to import it
import 'dart:convert' show jsonDecode;
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
...
and use it with
jsonDecode(response.body)
or
import 'dart:convert' show json;
with
json.decode(response.body)
The first variant was added to avoid conflicts when the variable holding the JSON value is named json.

How to show CircularProgressIndicator before Flutter App Start?

In my demo app I need to load a 2 JSON file from server. Both JSON has large data in it. I my Flutter app I call the json using Future + async + await than I call to create a widget with runApp. In the body I try to activate a CircularProgressIndicator. It shows appBar and its content as well as empty white page body and 4 or 5 seconds later loads the data in actual body.
My question is I need to show the CircularProgressIndicator first and once the data load I will call runApp(). How do I do that?
// MAIN
void main() async {
_isLoading = true;
// Get Currency Json
currencyData = await getCurrencyData();
// Get Weather Json
weatherData = await getWeatherData();
runApp(new MyApp());
}
// Body
body: _isLoading ?
new Center(child:
new CircularProgressIndicator(
backgroundColor: Colors.greenAccent.shade700,
)
) :
new Container(
//… actual UI
)
You need to put the data/or loading indicator inside a scaffold, show the scaffold everytime whether you have data or not, the content inside you can then do what you want to do.`
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Hello Rectangle',
home: Scaffold(
appBar: AppBar(
title: Text('Hello Rectangle'),
),
body: HelloRectangle(),
),
),
);
}
class HelloRectangle extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: Container(
color: Colors.greenAccent,
height: 400.0,
width: 300.0,
child: Center(
child: FutureBuilder(
future: buildText(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return CircularProgressIndicator(backgroundColor: Colors.blue);
} else {
return Text(
'Hello!',
style: TextStyle(fontSize: 40.0),
textAlign: TextAlign.center,
);
}
},
),
),
),
);
}
Future buildText() {
return new Future.delayed(
const Duration(seconds: 5), () => print('waiting'));
}
}
`