dart convert from model to map code example
Example 1: dart object to map
class Human {
String name;
int age;
Map<String, dynamic> toMap() {
return {
'name': name,
'age': age,
};
}
}
Example 2: flutter List> example
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context){
return MaterialApp(
title: 'Hello Phrases',
home: _MyHomePage(),
);
}
}
class _MyHomePage extends StatefulWidget{
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<_MyHomePage> {
int phraseCount = 0;
final List<Map<String, Object>> myPhraseList = [
{'phrase': 'Phrase 1 some interesting phrase'},
{'phrase': 'Phrase 2 and yet another interesting phrase'}
];
void nextPhrase(){
setState((){
phraseCount += 1;
});
}
void resetPhrase(){
setState((){
phraseCount = 0;
});
}
@override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: Text('The Quote App'),
),
body: Container(
padding: EdgeInsets.all(20.0),
child: phraseCount < myPhraseList.length ? PhraseLogic(nextPhrase: nextPhrase, myPhraseList: myPhraseList, phraseCount: phraseCount) : ResetPhrase(resetPhrase: resetPhrase),
),
);
}
}
class PhraseLogic extends StatelessWidget {
final List<Map<String, Object>> myPhraseList;
final int phraseCount;
final Function nextPhrase;
PhraseLogic({this.nextPhrase, this.phraseCount, this.myPhraseList});
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(myPhraseList[phraseCount]['phrase']),
SizedBox(height: 20.0),
RaisedButton(
child: Text('Next Phrase'),
onPressed: nextPhrase,
),
],
);
}
}
class ResetPhrase extends StatelessWidget {
final Function resetPhrase;
ResetPhrase({this.resetPhrase});
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('All done!!!'),
SizedBox(height: 20.0),
RaisedButton(
child: Text('Reset Phrase'),
onPressed: resetPhrase,
),
],
);
}
}