Flutter doesn't want to import json - 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.

Related

Why does my jsonDecode() method in Flutter throw a Format Exception?

I've been learning mobile development on Flutter for a while and currently trying to build a single-page text translation app, for exercise. I tried to integrate a Google Translate API.
I'm having trouble running the app due to an error (Format Exception) in the jsonDecode() method I use to extract the translation result json object (Post method HTTP request)
Here's my home screen code
import 'package:flutter/material.dart';
import '../models/input_model.dart';
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
TextEditingController textController = TextEditingController();
final translation = Sentence();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Translation App')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
////////////// Widget for the translation source text //////////////
Container(
width: MediaQuery.of(context).size.width / 1.5,
child: TextField(
controller: textController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(8)))),
)),
////////////////////////////////////////////////////////////////////
ElevatedButton(
onPressed: () {
Sentence.connectToAPI('en', 'de', textController.text); //static language option
setState(() {}); //input for testing
},
child: Text('Translate')),
////////////// Widget for the translation result text //////////////
Container(
width: MediaQuery.of(context).size.width / 1.5,
child: Text((translation.trans == null)
? 'no data'
: translation.trans.toString())),
],
),
),
);
}
}
And here's the model file where the problem lies:
import 'dart:convert';
import 'package:http/http.dart' as http;
class Sentence {
Sentence({
this.trans,
this.orig,
this.backend,
});
String? trans;
String? orig;
int? backend;
factory Sentence.fromJson(Map<String, dynamic> json) => Sentence(
trans: json["trans"],
orig: json["orig"],
backend: json["backend"],
);
Map<String, dynamic> toJson() => {
"trans": trans,
"orig": orig,
"backend": backend,
};
static Future<Sentence> connectToAPI(
String from, String to, String text) async {
String pathURL =
'https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e';
var response =
await http.post(Uri.parse(pathURL), headers: <String, String>{
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'PostmanRuntime/7.29.0'
}, body: {
'sl': from,
'tl': to,
'q': text
});
var jsonObject = jsonDecode(response.body); //the exception error message pointed here
var textObject = (jsonObject as Map<String, dynamic>)['sentences'];
return Sentence.fromJson(textObject);
}
}
The exception error message was:
FormatException (FormatException: Unexpected character (at character 1)
^
I'm still a newbie and it really confuses me. I tried to search for the explanation of the error message on Google but still having a hard time understanding it. What seems to be the problem here?

trying to make json request from worldtime api flutter

I am trying to make a JSON request from world time API by using future builder when I tried to get the data from my asset folder which contains JSON data it works properly but when I try to get the data from the internet it crashes
here as you can see
this the main class
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
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: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
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> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.green,
body: FutureBuilder(
future:
get('http://api.worldweatheronline.com/premium/v1/weather.ashx?key=65dbd1979bd445e58aa171529203010&q=Europe/London&format=json&num_of_days=1'),
builder: (context, snapshot) {
var myData = json.decode(snapshot.data.toString());
String jsonsDataString = myData.body.toString(); // toString of Response's body is assigned to jsonDataString
jsonsDataString = jsonDecode(jsonsDataString);
if (myData == null){
return Center(
child: Text(
'Loading',
style: TextStyle(fontSize: 30, color: Colors.red),
),
);
}else{
return Center(
child: Text(
myData,
style: TextStyle(fontSize: 30, color: Colors.red),
),
);
}
}));
}
}
this the error when I try to run the app
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following FormatException was thrown building FutureBuilder<Response>(dirty, state: _FutureBuilderState<Response>#2a0b7):
Unexpected character (at character 1)
Instance of 'Response'
^
The relevant error-causing widget was:
FutureBuilder<Response> file:///F:/FlutterProjects/learn_json/lib/main.dart:54:15
When the exception was thrown, this was the stack:
#0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1394:5)
#1 _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1261:9)
#2 _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:926:22)
#3 _parseJson (dart:convert-patch/convert_patch.dart:31:10)
#4 JsonDecoder.convert (dart:convert/json.dart:495:36)
...
your key is not working , check it using Postman , and you have to await for the response

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

how to open a 'csv file' like 'url launcher' in Flutter

i converted list into File of .csv extension then
tried OpenFile.open and ended up with error No permissions found in manifest for: 2, tried canLaunch and ended up with error name.csv exposed beyond app through Intent.getData(), Failed to handle method call
so how to open that csv file in any 3rd part application.
You can copy paste run full code below
and make sure you have a file /sdcard/Download/sample.csv, see picture below
You also need CSV Viewer installed in your Emulator
code snippet
final filePath = '/sdcard/Download/sample.csv';
print('${filePath}');
final message = await OpenFile.open(filePath);
working demo
device file explorer
full code
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:open_file/open_file.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _openResult = 'Unknown';
Future<void> openFile() async {
//final filePath = '/sdcard/Download/sample.pdf';
final filePath = '/sdcard/Download/sample.csv';
print('${filePath}');
final message = await OpenFile.open(filePath);
setState(() {
_openResult = message;
});
}
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('open result: $_openResult\n'),
FlatButton(
child: Text('Tap to open file'),
onPressed: openFile,
),
],
),
),
),
);
}
}

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