Browse Source

added person class with de/serialization

Ray-works 9 months ago
parent
commit
924c049adb
7 changed files with 312 additions and 35 deletions
  1. 5 0
      .autogit/autogit.json
  2. 25 0
      lib/models/person.dart
  3. 33 0
      lib/person_details.dart
  4. 12 8
      lib/router.dart
  5. 111 27
      lib/startseite.dart
  6. 125 0
      pubspec.lock
  7. 1 0
      pubspec.yaml

+ 5 - 0
.autogit/autogit.json

@@ -0,0 +1,5 @@
1
+{
2
+  "updateInterval": 1800,
3
+  "logging": true,
4
+  "silent": true
5
+}

+ 25 - 0
lib/models/person.dart

@@ -0,0 +1,25 @@
1
+import 'dart:convert';
2
+
3
+class Person {
4
+  String firstname;
5
+  String lastname;
6
+  int age;
7
+  String gender;
8
+
9
+  Person(this.firstname, this.lastname, this.age, this.gender);
10
+
11
+  String toJson(){
12
+    Map<String, dynamic> map = Map<String, dynamic>();
13
+    map['firstname'] = this.firstname;
14
+    map['lastname'] = this.lastname;
15
+    map['age'] = this.age;
16
+    map['gender'] = this.gender;
17
+
18
+    return jsonEncode(map);
19
+  }
20
+
21
+  static Person fromJson(String json){
22
+    Map<String, dynamic> map = jsonDecode(json);
23
+    return Person(map['firstname'], map['lastname'], map['age'], map['gender']);
24
+  }
25
+}

+ 33 - 0
lib/person_details.dart

@@ -0,0 +1,33 @@
1
+import 'dart:convert';
2
+import 'package:flutter/material.dart';
3
+import 'models/person.dart';
4
+
5
+class PersonDetails extends StatelessWidget {
6
+  PersonDetails(this.person);
7
+  Person person;
8
+
9
+  @override
10
+  Widget build(BuildContext context) {
11
+    return Scaffold(
12
+      body: SafeArea(
13
+        child: 
14
+        Padding(
15
+          padding: EdgeInsets.all(20),
16
+          child: Container(
17
+            alignment: Alignment.topLeft,
18
+            child: Column(
19
+              mainAxisAlignment: MainAxisAlignment.start,
20
+              crossAxisAlignment: CrossAxisAlignment.start,
21
+              children: [
22
+                Text("${person.firstname} ${person.lastname}", style: TextStyle(fontSize: 32, fontWeight: FontWeight.bold)),
23
+                Divider(),
24
+                Text("Alter: ${person.age}"),
25
+                Text("Geschlecht: ${person.gender}")
26
+              ],
27
+              )
28
+            ),
29
+        ),
30
+      )
31
+    );
32
+  }
33
+}

+ 12 - 8
lib/router.dart

@@ -1,22 +1,26 @@
1 1
 import 'package:flutter/material.dart';
2
+import 'models/person.dart';
2 3
 import 'startseite.dart';
3 4
 import 'zweiteseite.dart';
5
+import 'person_details.dart';
4 6
 
5 7
 const StartSeiteRoute = '/';
6 8
 const ZweiteSeiteRoute = '/zweiteseite';
9
+const PersonDetailsRoute = '/persondetails';
7 10
 
8 11
 class MyRouter {
9 12
   static Route<dynamic> routes(RouteSettings settings) {
10 13
     switch (settings.name) {
11 14
       case StartSeiteRoute:
12
-        return MaterialPageRoute(
13
-            builder: (BuildContext context) => StartSeite());
14
-      case ZweiteSeiteRoute:
15
-        {
16
-          String daten = settings.arguments;
17
-          return MaterialPageRoute(
18
-              builder: (BuildContext context) => ZweiteSeite(daten));
19
-        }
15
+        return MaterialPageRoute(builder: (BuildContext context) => StartSeite());
16
+      case ZweiteSeiteRoute: {
17
+        String daten = settings.arguments;
18
+        return MaterialPageRoute(builder: (BuildContext context) => ZweiteSeite(daten));
19
+      }
20
+      case PersonDetailsRoute: {
21
+        Person person = settings.arguments;
22
+        return MaterialPageRoute(builder: (context) => PersonDetails(person));
23
+      }
20 24
     }
21 25
   }
22 26
 }

+ 111 - 27
lib/startseite.dart

@@ -1,43 +1,64 @@
1 1
 import 'dart:convert';
2 2
 import 'package:http/http.dart' as http;
3 3
 import 'package:flutter/material.dart';
4
+import 'package:my_first_app/person_details.dart';
4 5
 import 'package:my_first_app/router.dart';
6
+import 'package:shared_preferences/shared_preferences.dart';
7
+import 'models/person.dart';
5 8
 
6 9
 class StartSeite extends StatefulWidget {
7 10
   _StartSeiteState createState() => _StartSeiteState();
8 11
 }
9 12
 
10 13
 class _StartSeiteState extends State<StartSeite> {
11
-  Future<String> fetchName() async {
14
+  Future<String> fetchPerson() async {
12 15
     final person = await http.get('https://randomname.de/?format=json&count=1');
13
-    String vorname = "";
16
+    dynamic json = "";
14 17
     if (person != null) {
15 18
       if (person.statusCode == 200) {
16 19
         // print(person.body);
17
-        final personArray = jsonDecode(person.body);
18
-        final konkretePerson = personArray[0];
19
-        vorname = konkretePerson['firstname'];
20
+        // final personArray = jsonDecode(person.body);
21
+        // final konkretePerson = personArray[0];
22
+        // vorname = konkretePerson['firstname'];
20 23
         // print('Vorname: $vorname');
21 24
         // print('Mein StatusCode: ${person.statusCode}');
25
+        return Future.value(person.body);
22 26
       }
23 27
     }
24
-    return Future.value(vorname);
28
+    return Future.value(json);
25 29
   }
26 30
 
27
-  List<String> generatedNames = List<String>();
31
+  @override
32
+  void initState() { 
33
+    super.initState();
34
+    printPreferences();
35
+  }
36
+
37
+  void printPreferences() async {
38
+    SharedPreferences prefs = await _prefs;
39
+    print(prefs.getInt("anzahlPersonen"));
40
+
41
+    String personjson = prefs.getString("Person");
42
+    Person p = Person.fromJson(personjson);
43
+    print("${p.firstname} ${p.lastname}");
44
+  }
45
+
46
+  List<Person> generatedPersons = List<Person>();
28 47
   final listScrollController = ScrollController();
29
-  String empfangeneDaten;
48
+
49
+  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
50
+  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
30 51
 
31 52
   @override
32 53
   Widget build(BuildContext context) {
33 54
     return Scaffold(
55
+        key: scaffoldKey,
34 56
         body: Center(
35 57
             child: Column(
36 58
       mainAxisAlignment: MainAxisAlignment.center,
37 59
       crossAxisAlignment: CrossAxisAlignment.start,
38 60
       children: [
39 61
         SizedBox(height: 45),
40
-        Text('Empfangene Daten:' + (empfangeneDaten ?? "Keine Daten")),
41 62
         Expanded(
42 63
           child: Container(
43 64
               alignment: Alignment.center,
@@ -45,10 +66,12 @@ class _StartSeiteState extends State<StartSeite> {
45 66
                 controller: listScrollController,
46 67
                 separatorBuilder: (context, index) =>
47 68
                     Divider(height: 0.5, color: Colors.blue),
48
-                itemCount: generatedNames.length,
69
+                itemCount: generatedPersons.length,
49 70
                 itemBuilder: (BuildContext context, int index) {
71
+                  String vorname = generatedPersons[index].firstname;
50 72
                   return ListTile(
51
-                    title: Text(generatedNames[index]),
73
+                    title: Text(vorname),
74
+                    onTap: () => Navigator.pushNamed(context, PersonDetailsRoute, arguments: generatedPersons[index])
52 75
                   );
53 76
                 },
54 77
               )),
@@ -58,25 +81,86 @@ class _StartSeiteState extends State<StartSeite> {
58 81
                 color: Colors.black,
59 82
                 splashColor: Colors.blue,
60 83
                 onPressed: () async {
61
-                  // await fetchName().then((value) {
62
-                  //   if (value.isNotEmpty) {
63
-                  //     setState(() {
64
-                  //       generatedNames.add(value);
65
-                  //       listScrollController.jumpTo(
66
-                  //           listScrollController.position.maxScrollExtent);
67
-                  //     });
68
-                  //   }
84
+                  // var jsondata = '[{"firstname":"Annetraude","lastname":"Kreutzer","gender":"f","birthday":"26.11.2001","email":"Annetraude-Kreutzer@solar-impact.pro","age":18,"password":"ahX*u8Ahm)","username":"Moatmour01","location":{"zip":"67744","city":"Schweinschied","street":{"name":"Am Klingenberg","number":20}}}]';
85
+                  // var decoded = jsonDecode(jsondata);
86
+                  // Person p = Person(decoded[0]['firstname'], decoded[0]['lastname'], decoded[0]['age'], decoded[0]['gender']);
87
+                  // print(p);
88
+                  String firstname = "";
89
+                  await fetchPerson().then((value) async {
90
+                    if (value.isNotEmpty) {
91
+                      var json = jsonDecode(value)[0];
92
+                      Person p = Person(json['firstname'], json['lastname'], json['age'], json['gender']);
93
+                      SharedPreferences prefs = await _prefs;
94
+                      firstname = json['firstname'];
95
+
96
+                      setState(() {
97
+                        generatedPersons.add(p);
98
+                        prefs.setInt("anzahlPersonen", generatedPersons.length);
99
+                        prefs.setString("Person", p.toJson());
100
+                        listScrollController.jumpTo(
101
+                            listScrollController.position.maxScrollExtent);
102
+                      });
103
+                      
104
+                    }
105
+                  });
106
+
107
+                  SnackBar sb = SnackBar(
108
+                    content: Text("$firstname wurde angelegt.")
109
+                  );
110
+
111
+                  AlertDialog alert = AlertDialog(
112
+                    title: Text("Neue Person"),
113
+                    content: Text("Es wurde eine neue Person angelegt: $firstname"),
114
+                    actions: [
115
+                      Column(
116
+                        children: [
117
+                          FlatButton(
118
+                            child: Text("Ok"),
119
+                            onPressed: (){
120
+                              Navigator.of(context).pop();
121
+                            },
122
+                          ),
123
+                          FlatButton(
124
+                            child: Text("Cancel", style: TextStyle(color: Colors.red)),
125
+                            onPressed: (){
126
+                              Navigator.pop(context);
127
+                            },
128
+                          ),
129
+                        ],
130
+                      )
131
+                      
132
+                    ],
133
+                  );
134
+
135
+                  // showDialog(context: context, builder: (context){
136
+                  //   return alert;
69 137
                   // });
70
-                  var result = await Navigator.pushNamed(
71
-                      context, ZweiteSeiteRoute,
72
-                      arguments: 'Daten von der Startseite');
73
-                  setState(() {
74
-                    empfangeneDaten = result;
75
-                    print(result);
138
+
139
+                  // scaffoldKey.currentState.showSnackBar(sb);
140
+                  // var result = await Navigator.pushNamed(
141
+                  //     context, ZweiteSeiteRoute,
142
+                  //     arguments: 'Daten von der Startseite');
143
+                  // setState(() {
144
+                  //   empfangeneDaten = result;
145
+                  //   print(result);
146
+                  // });
147
+                },
148
+                child: Text("Gib mir einen Namen", style: TextStyle(color: Colors.white))
149
+              )
150
+            ),
151
+            Center(
152
+              child: RaisedButton(
153
+                onPressed: () async {
154
+                  SharedPreferences prefs = await _prefs;
155
+                  setState(()  {
156
+                    generatedPersons.clear();
157
+                    prefs.setInt("anzahlPersonen", 0);
76 158
                   });
77 159
                 },
78
-                child: Text("Gib mir einen Namen",
79
-                    style: TextStyle(color: Colors.white))))
160
+                child: Text("Liste leeren")
161
+              ),
162
+            )
163
+
80 164
       ],
81 165
     )));
82 166
   }

+ 125 - 0
pubspec.lock

@@ -57,6 +57,20 @@ packages:
57 57
       url: "https://pub.dartlang.org"
58 58
     source: hosted
59 59
     version: "1.2.0-nullsafety.1"
60
+  ffi:
61
+    dependency: transitive
62
+    description:
63
+      name: ffi
64
+      url: "https://pub.dartlang.org"
65
+    source: hosted
66
+    version: "0.1.3"
67
+  file:
68
+    dependency: transitive
69
+    description:
70
+      name: file
71
+      url: "https://pub.dartlang.org"
72
+    source: hosted
73
+    version: "5.2.1"
60 74
   flutter:
61 75
     dependency: "direct main"
62 76
     description: flutter
@@ -67,6 +81,11 @@ packages:
67 81
     description: flutter
68 82
     source: sdk
69 83
     version: "0.0.0"
84
+  flutter_web_plugins:
85
+    dependency: transitive
86
+    description: flutter
87
+    source: sdk
88
+    version: "0.0.0"
70 89
   http:
71 90
     dependency: "direct main"
72 91
     description:
@@ -81,6 +100,13 @@ packages:
81 100
       url: "https://pub.dartlang.org"
82 101
     source: hosted
83 102
     version: "3.1.4"
103
+  intl:
104
+    dependency: transitive
105
+    description:
106
+      name: intl
107
+      url: "https://pub.dartlang.org"
108
+    source: hosted
109
+    version: "0.16.1"
84 110
   matcher:
85 111
     dependency: transitive
86 112
     description:
@@ -102,6 +128,27 @@ packages:
102 128
       url: "https://pub.dartlang.org"
103 129
     source: hosted
104 130
     version: "1.8.0-nullsafety.1"
131
+  path_provider_linux:
132
+    dependency: transitive
133
+    description:
134
+      name: path_provider_linux
135
+      url: "https://pub.dartlang.org"
136
+    source: hosted
137
+    version: "0.0.1+2"
138
+  path_provider_platform_interface:
139
+    dependency: transitive
140
+    description:
141
+      name: path_provider_platform_interface
142
+      url: "https://pub.dartlang.org"
143
+    source: hosted
144
+    version: "1.0.3"
145
+  path_provider_windows:
146
+    dependency: transitive
147
+    description:
148
+      name: path_provider_windows
149
+      url: "https://pub.dartlang.org"
150
+    source: hosted
151
+    version: "0.0.4+1"
105 152
   pedantic:
106 153
     dependency: transitive
107 154
     description:
@@ -109,6 +156,69 @@ packages:
109 156
       url: "https://pub.dartlang.org"
110 157
     source: hosted
111 158
     version: "1.9.2"
159
+  platform:
160
+    dependency: transitive
161
+    description:
162
+      name: platform
163
+      url: "https://pub.dartlang.org"
164
+    source: hosted
165
+    version: "2.2.1"
166
+  plugin_platform_interface:
167
+    dependency: transitive
168
+    description:
169
+      name: plugin_platform_interface
170
+      url: "https://pub.dartlang.org"
171
+    source: hosted
172
+    version: "1.0.3"
173
+  process:
174
+    dependency: transitive
175
+    description:
176
+      name: process
177
+      url: "https://pub.dartlang.org"
178
+    source: hosted
179
+    version: "3.0.13"
180
+  shared_preferences:
181
+    dependency: "direct main"
182
+    description:
183
+      name: shared_preferences
184
+      url: "https://pub.dartlang.org"
185
+    source: hosted
186
+    version: "0.5.12"
187
+  shared_preferences_linux:
188
+    dependency: transitive
189
+    description:
190
+      name: shared_preferences_linux
191
+      url: "https://pub.dartlang.org"
192
+    source: hosted
193
+    version: "0.0.2+2"
194
+  shared_preferences_macos:
195
+    dependency: transitive
196
+    description:
197
+      name: shared_preferences_macos
198
+      url: "https://pub.dartlang.org"
199
+    source: hosted
200
+    version: "0.0.1+10"
201
+  shared_preferences_platform_interface:
202
+    dependency: transitive
203
+    description:
204
+      name: shared_preferences_platform_interface
205
+      url: "https://pub.dartlang.org"
206
+    source: hosted
207
+    version: "1.0.4"
208
+  shared_preferences_web:
209
+    dependency: transitive
210
+    description:
211
+      name: shared_preferences_web
212
+      url: "https://pub.dartlang.org"
213
+    source: hosted
214
+    version: "0.1.2+7"
215
+  shared_preferences_windows:
216
+    dependency: transitive
217
+    description:
218
+      name: shared_preferences_windows
219
+      url: "https://pub.dartlang.org"
220
+    source: hosted
221
+    version: "0.0.1+1"
112 222
   sky_engine:
113 223
     dependency: transitive
114 224
     description: flutter
@@ -170,5 +280,20 @@ packages:
170 280
       url: "https://pub.dartlang.org"
171 281
     source: hosted
172 282
     version: "2.1.0-nullsafety.3"
283
+  win32:
284
+    dependency: transitive
285
+    description:
286
+      name: win32
287
+      url: "https://pub.dartlang.org"
288
+    source: hosted
289
+    version: "1.7.3"
290
+  xdg_directories:
291
+    dependency: transitive
292
+    description:
293
+      name: xdg_directories
294
+      url: "https://pub.dartlang.org"
295
+    source: hosted
296
+    version: "0.1.2"
173 297
 sdks:
174 298
   dart: ">=2.10.0-110 <2.11.0"
299
+  flutter: ">=1.12.13+hotfix.5 <2.0.0"

+ 1 - 0
pubspec.yaml

@@ -24,6 +24,7 @@ dependencies:
24 24
   flutter:
25 25
     sdk: flutter
26 26
   http: ^0.12.2
27
+  shared_preferences: ^0.5.12
27 28
 
28 29
 
29 30
   # The following adds the Cupertino Icons font to your application.