local JSON results are not shwoing - Flutter - json

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(),
);
}
}

Related

Flutter. Add a json.decode value to a String that can be used in the UI

Maybe this is a simple question, but I can't find the answer to it.
My app has 2 screens. 1st has a single button
onPressed: () {
fetchCurrentTitle();
Navigator.push(context,
MaterialPageRoute(builder: (context) => Screen2Widget()));
},
fetchCurrentTitle() method fetches data from json and decodes it.
I can see the return using:
final streamFullTitle = json.decode(response.body)['data'][0]['title'];
print(streamFullTitle);
I get the desired response of the current title in the console.
In the 2nd screen I have a hardcoded List. Where items have these values:
class List {
String id;
String streamer;
String logoUrl;
String title;
}
The first three attribute in List class dont need to change so they are hardcoded. I just need to assign the title value fromfetchCurrentTitle() to the String title. in class List.
Look of one of my list items
My fetchCurrentTitle() works as intended
Future<String> fetchCurrentTitle() async {
http.Response response = await http.get(...
I want the user to push the button on the first screen to go to the second screen and show a spinner with title "looking for title" and then get the new title instead of waiting fetchCurrentTitle() to complete only entering the second screen.
Thank you in advance.
You can try to run your fetchCurrentTitle() in the second screen on
void initState() {
super.initState();
fetchCurrentTitle()
/// show or set visibility for loading spinner
}
After you get the title value, you can simply assign new title by
List existingList = new List(id,streamer,logoUrl,title);
existingList.id = titleValueFromApi
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sample_project_for_api/Employee.dart';
void main() => runApp(MaterialApp(
title: "App",
home: MyApp(),
));
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('home page'),
),
body: Center(
child: Padding(
padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
child: RaisedButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => SecondScreen()));
},
child: const Text('First Page')),
)),
);
}
}
class SecondScreen extends StatefulWidget {
#override
_SecondScreenState createState() => _SecondScreenState();
}
class _SecondScreenState extends State<SecondScreen> {
bool _isLoading = false;
Employee sampleData;
#override
void initState() {
super.initState();
getYouData();
}
Future<String> loadPersonFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
getYouData() async {
setState(() {
_isLoading = true;
});
String jsonString = await loadPersonFromAssets();
final data = employeeFromJson(jsonString);
sampleData = data;
// this is where you get the data from the network
Future.delayed(const Duration(seconds: 5), () {
// this is sample delay for you to know the delay.
// you can say this is loading your data
setState(() {
_isLoading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Container(
child: _isLoading
//here give your message getting the title
? CircularProgressIndicator()
: Card(
child: Column(
children: <Widget>[
Text('your 1st hardcoded text'),
Text('your 2st hardcoded text'),
Text('your 3st hardcoded text'),
Text(
'This is your dynamic data after fetching :${sampleData.employeeName}')
],
),
),
),
),
),
);
}
}
check out this example you will give you an idea of what to do
1) going from one page to another page
2) loading you data , while that showing the spinner
3) on fetching the data update the UI.
let me know about this.
Thanks.
Try this,
import 'dart:convert';
import "package:flutter/material.dart";
import 'package:http/http.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: Page1(),
);
}
}
class Page1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Page 1")),
body: Center(
child: RaisedButton(
child: Text("Goto Page2"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Page2(),
),
);
},
),
),
);
}
}
class Page2 extends StatefulWidget {
#override
_Page2State createState() => _Page2State();
}
class _Page2State extends State<Page2> {
Future<void> _initLoader;
String _title;
#override
void initState() {
_initLoader = _loadInitData();
super.initState();
}
Future<void> _loadInitData() async {
await Future.delayed(Duration(seconds: 2));
//_title = await fetchCurrentTitle();
_title = "This is the Loaded Title";
}
Future<String> fetchCurrentTitle() async {
Response response = await get("...");
return json.decode(response.body)['data'][0]['title'];
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Page 2")),
body: FutureBuilder(
future: _initLoader,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
CircularProgressIndicator(),
const SizedBox(height: 8.0),
Text("Looking for Title"),
],
),
);
else if (snapshot.hasError)
return Center(
child: Text("Error: ${snapshot.error}"),
);
else
return Center(
child: Text("$_title"),
);
},
),
);
}
}

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

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]]

Is there a way to have an argument with two types in Dart?

For navigation, I built a simple factory class that generates a ListTile that pushes a route to the Navigator:
static Widget simpleNavRow(String text, BuildContext context, String route) {
return Column(
children: <Widget>[
ListTile(
title: Text(text),
onTap: () {
Navigator.pushNamed(context, route);
},
),
Divider(),
],
);
}
However, I soon realized that it would be convenient to support pushing widgets as well (or instantiate from their class if possible). I couldn't figure out how to make the "route" argument accept either a String or a Widget, so I created a class that initializes with one of those two types. This code works, but is there a better way to achieve this?
class NavTo {
String route;
Widget widget;
NavTo.route(this.route);
NavTo.widget(this.widget);
push(BuildContext context) {
if (route != null) {
Navigator.pushNamed(context, route);
}
if (widget != null) {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return widget;
}));
}
}
}
class ListHelper {
static final padding = EdgeInsets.all(12.0);
static Widget simpleNavRow(String text, BuildContext context, NavTo navTo) {
return Column(
children: <Widget>[
ListTile(
title: Text(text),
onTap: () {
navTo.push(context);
},
),
Divider(),
],
);
}
}
// usage:
// ListHelper.simpleNavRow('MyWidget', context, NavTo.widget(MyWidget()))
Since you are expecting one of multiple types, what about having dynamic and then in the push method of NavTo, you could check the type:
class NavTo {
dynamic route;
push(BuildContext context) {
if (route is String) {
...
} else if (route is Widget) {
...
}
}
}
I don’t believe the union type is available in Dart. I like your solution over the use of dynamic as it is strongly typed.
You could use named parameters.
NavTo({this.route,this.widget})
But then you don’t have compile-type checking for one and only one parameter.
The only improvement I would make to your constructors is to add #required.
Personnally i like to give Items a MaterialPageRoute params
static Widget simpleNavRow(String text, BuildContext context, MaterialPageRoute route) {
return Column(
children: <Widget>[
ListTile(
title: Text(text),
onTap: () {
Navigator.push(context, route);
},
),
Divider(),
],);
}
items stays dumb like this and i decide what they do in the parent.
After you can create an item factory for each type you have that initialize the correct route like this :
class ItemExemple extends StatelessWidget {
final String text;
final MaterialPageRoute route;
ItemExemple(this.text, this.route);
factory ItemExemple.typeA(String text, BuildContext context) =>
new ItemExemple(text, new MaterialPageRoute(builder: (context) => new ItemA()));
factory ItemExemple.typeB(String text, BuildContext context) =>
new ItemExemple(text, new MaterialPageRoute(builder: (context) => new ItemB()));
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
ListTile(
title: Text(this.text),
onTap: () {
Navigator.push(context, route);
},
),
Divider(),
],);
}
}

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'));
}
}
`