Browse Source

added network check

Eray Sönmez 9 months ago
parent
commit
712cf82864
10 changed files with 292 additions and 145 deletions
  1. 13 0
      .vscode/launch.json
  2. 1 1
      android/app/build.gradle
  3. 3 3
      lib/main.dart
  4. 3 3
      lib/models/person.dart
  5. 60 0
      lib/personhinzufuegen.dart
  6. 16 8
      lib/router.dart
  7. 127 127
      lib/startseite.dart
  8. 39 0
      lib/utils/network.dart
  9. 28 0
      pubspec.lock
  10. 2 3
      pubspec.yaml

+ 13 - 0
.vscode/launch.json

@@ -0,0 +1,13 @@
1
+{
2
+    // Use IntelliSense to learn about possible attributes.
3
+    // Hover to view descriptions of existing attributes.
4
+    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
+    "version": "0.2.0",
6
+    "configurations": [
7
+        {
8
+            "name": "my_first_app",
9
+            "request": "launch",
10
+            "type": "dart"
11
+        }
12
+    ]
13
+}

+ 1 - 1
android/app/build.gradle

@@ -27,7 +27,7 @@ apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
27 27
 
28 28
 android {
29 29
     compileSdkVersion 29
30
-
30
+    
31 31
     sourceSets {
32 32
         main.java.srcDirs += 'src/main/kotlin'
33 33
     }

+ 3 - 3
lib/main.dart

@@ -1,10 +1,10 @@
1
-import 'dart:convert';
2
-import 'dart:math';
3
-import 'package:http/http.dart' as http;
4 1
 import 'package:flutter/material.dart';
2
+import 'package:my_first_app/utils/network.dart';
5 3
 import 'router.dart';
6 4
 
7 5
 void main() {
6
+  WidgetsFlutterBinding.ensureInitialized();
7
+  Network.init();
8 8
   runApp(MyApp());
9 9
 }
10 10
 

+ 3 - 3
lib/models/person.dart

@@ -8,7 +8,7 @@ class Person {
8 8
 
9 9
   Person(this.firstname, this.lastname, this.age, this.gender);
10 10
 
11
-  String toJson(){
11
+  String toJson() {
12 12
     Map<String, dynamic> map = Map<String, dynamic>();
13 13
     map['firstname'] = this.firstname;
14 14
     map['lastname'] = this.lastname;
@@ -18,8 +18,8 @@ class Person {
18 18
     return jsonEncode(map);
19 19
   }
20 20
 
21
-  static Person fromJson(String json){
21
+  static Person fromJson(String json) {
22 22
     Map<String, dynamic> map = jsonDecode(json);
23 23
     return Person(map['firstname'], map['lastname'], map['age'], map['gender']);
24 24
   }
25
-}
25
+}

+ 60 - 0
lib/personhinzufuegen.dart

@@ -0,0 +1,60 @@
1
+import 'package:flutter/material.dart';
2
+import 'package:shared_preferences/shared_preferences.dart';
3
+
4
+import 'models/person.dart';
5
+
6
+class PersonHinzufuegen extends StatefulWidget {
7
+  @override
8
+  PersonHinzufuegenState createState() => PersonHinzufuegenState();
9
+}
10
+
11
+class PersonHinzufuegenState extends State<PersonHinzufuegen> {
12
+  @override
13
+  Widget build(BuildContext context) {
14
+    Person p = Person('', '', 0, '');
15
+
16
+    return Scaffold(
17
+        body: SafeArea(
18
+            child: Padding(
19
+                padding: EdgeInsets.only(left: 25, top: 10),
20
+                child: Column(
21
+                  children: [
22
+                    TextField(
23
+                      decoration: InputDecoration(labelText: "Vorname"),
24
+                      onChanged: (value) {
25
+                        p.firstname = value;
26
+                      },
27
+                    ),
28
+                    TextField(
29
+                      decoration: InputDecoration(labelText: "Nachname"),
30
+                      onChanged: (value) {
31
+                        p.lastname = value;
32
+                      },
33
+                    ),
34
+                    TextField(
35
+                      decoration: InputDecoration(labelText: "Alter"),
36
+                      keyboardType: TextInputType.number,
37
+                      onChanged: (value) {
38
+                        p.age = int.parse(value);
39
+                      },
40
+                    ),
41
+                    TextField(
42
+                      decoration: InputDecoration(labelText: "Geschlecht"),
43
+                      onChanged: (value) {
44
+                        p.gender = value;
45
+                      },
46
+                    ),
47
+                    RaisedButton(
48
+                        onPressed: () async {
49
+                          SharedPreferences prefs = await SharedPreferences.getInstance();
50
+                          List<String> personenliste = prefs.getStringList("Personenliste") ?? List<String>();
51
+                          personenliste.add(p.toJson());
52
+                          prefs.setStringList("Personenliste", personenliste);
53
+
54
+                          Navigator.pop(context, true);
55
+                        },
56
+                        child: Text("Hinzufügen"))
57
+                  ],
58
+                ))));
59
+  }
60
+}

+ 16 - 8
lib/router.dart

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

+ 127 - 127
lib/startseite.dart

@@ -1,8 +1,9 @@
1
+import 'dart:async';
1 2
 import 'dart:convert';
2 3
 import 'package:http/http.dart' as http;
3 4
 import 'package:flutter/material.dart';
4
-import 'package:my_first_app/person_details.dart';
5 5
 import 'package:my_first_app/router.dart';
6
+import 'package:my_first_app/utils/network.dart';
6 7
 import 'package:shared_preferences/shared_preferences.dart';
7 8
 import 'models/person.dart';
8 9
 
@@ -18,12 +19,6 @@ class _StartSeiteState extends State<StartSeite> {
18 19
     dynamic json = "";
19 20
     if (person != null) {
20 21
       if (person.statusCode == 200) {
21
-        // print(person.body);
22
-        // final personArray = jsonDecode(person.body);
23
-        // final konkretePerson = personArray[0];
24
-        // vorname = konkretePerson['firstname'];
25
-        // print('Vorname: $vorname');
26
-        // print('Mein StatusCode: ${person.statusCode}');
27 22
         return Future.value(person.body);
28 23
       }
29 24
     }
@@ -31,20 +26,25 @@ class _StartSeiteState extends State<StartSeite> {
31 26
   }
32 27
 
33 28
   @override
34
-  void initState() { 
29
+  void initState() {
35 30
     super.initState();
36 31
     printPreferences();
32
+    Network.registerSubscription(updateUI);
33
+  }
34
+
35
+  void updateUI() {
36
+    setState(() {});
37 37
   }
38 38
 
39 39
   void printPreferences() async {
40 40
     SharedPreferences prefs = await _prefs;
41 41
     setState(() {
42
-      List<String> personenliste = List<String>();
43
-      personenliste = prefs.getStringList("Personenliste");
44
-        for(String pjson in personenliste){
45
-          print("Reading: $pjson");
46
-          generatedPersons.add(Person.fromJson(pjson));
47
-        }
42
+      generatedPersons.clear();
43
+      List<String> personenliste = prefs.getStringList("Personenliste") ?? List<String>();
44
+      for (String pjson in personenliste) {
45
+        print("Reading: $pjson");
46
+        generatedPersons.add(Person.fromJson(pjson));
47
+      }
48 48
     });
49 49
   }
50 50
 
@@ -59,122 +59,122 @@ class _StartSeiteState extends State<StartSeite> {
59 59
         key: scaffoldKey,
60 60
         body: Center(
61 61
             child: Column(
62
-      mainAxisAlignment: MainAxisAlignment.center,
63
-      crossAxisAlignment: CrossAxisAlignment.start,
64
-      children: [
65
-        SizedBox(height: 45),
66
-        Expanded(
67
-          child: Container(
68
-              alignment: Alignment.center,
69
-              child: ListView.separated(
70
-                controller: listScrollController,
71
-                separatorBuilder: (context, index) =>
72
-                    Divider(height: 0.5, color: Colors.blue),
73
-                itemCount: generatedPersons.length,
74
-                itemBuilder: (BuildContext context, int index) {
75
-                  String vorname = generatedPersons[index].firstname;
76
-                  return ListTile(
77
-                    title: Text(vorname),
78
-                    onTap: () => Navigator.pushNamed(context, PersonDetailsRoute, arguments: generatedPersons[index])
79
-                  );
80
-                },
81
-              )),
82
-        ),
83
-        Center(
84
-            child: RaisedButton(
85
-                color: Colors.black,
86
-                splashColor: Colors.blue,
87
-                onPressed: () async {
88
-                  // 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}}}]';
89
-                  // var decoded = jsonDecode(jsondata);
90
-                  // Person p = Person(decoded[0]['firstname'], decoded[0]['lastname'], decoded[0]['age'], decoded[0]['gender']);
91
-                  // print(p);
92
-                  String firstname = "";
93
-                  await fetchPerson().then((value) async {
94
-                    if (value.isNotEmpty) {
95
-                      var json = jsonDecode(value)[0];
96
-                      Person p = Person(json['firstname'], json['lastname'], json['age'], json['gender']);
97
-                      SharedPreferences prefs = await _prefs;
98
-                      firstname = json['firstname'];
99
-
100
-                      setState(() {
101
-                        generatedPersons.add(p);
102
-
103
-                        List<String> personenliste = List<String>();
104
-
105
-                        for(Person pobj in generatedPersons){
106
-                          print("Writing: ${pobj.toJson()}");
107
-                          personenliste.add(pobj.toJson());
108
-                        }
109
-
110
-                        prefs.setStringList("Personenliste", personenliste);
111
-
112
-                        listScrollController.jumpTo(
113
-                            listScrollController.position.maxScrollExtent);
114
-
115
-                      });
116
-                      
117
-                    }
118
-                  });
119
-
120
-                  SnackBar sb = SnackBar(
121
-                    content: Text("$firstname wurde angelegt.")
122
-                  );
123
-
124
-                  AlertDialog alert = AlertDialog(
125
-                    title: Text("Neue Person"),
126
-                    content: Text("Es wurde eine neue Person angelegt: $firstname"),
127
-                    actions: [
128
-                      Column(
129
-                        children: [
130
-                          FlatButton(
131
-                            child: Text("Ok"),
132
-                            onPressed: (){
133
-                              Navigator.of(context).pop();
134
-                            },
135
-                          ),
136
-                          FlatButton(
137
-                            child: Text("Cancel", style: TextStyle(color: Colors.red)),
138
-                            onPressed: (){
139
-                              Navigator.pop(context);
140
-                            },
141
-                          ),
142
-                        ],
143
-                      )
144
-                      
145
-                    ],
146
-                  );
147
-
148
-                  // showDialog(context: context, builder: (context){
149
-                  //   return alert;
150
-                  // });
151
-
152
-                  // scaffoldKey.currentState.showSnackBar(sb);
153
-                  // var result = await Navigator.pushNamed(
154
-                  //     context, ZweiteSeiteRoute,
155
-                  //     arguments: 'Daten von der Startseite');
156
-                  // setState(() {
157
-                  //   empfangeneDaten = result;
158
-                  //   print(result);
159
-                  // });
160
-                },
161
-                child: Text("Gib mir einen Namen", style: TextStyle(color: Colors.white))
162
-              )
62
+          mainAxisAlignment: MainAxisAlignment.center,
63
+          crossAxisAlignment: CrossAxisAlignment.start,
64
+          children: [
65
+            SizedBox(height: 45),
66
+            Expanded(
67
+              child: Container(
68
+                  alignment: Alignment.center,
69
+                  child: ListView.separated(
70
+                    controller: listScrollController,
71
+                    separatorBuilder: (context, index) => Divider(height: 0.5, color: Colors.blue),
72
+                    itemCount: generatedPersons.length,
73
+                    itemBuilder: (BuildContext context, int index) {
74
+                      String vorname = generatedPersons[index].firstname;
75
+                      return ListTile(title: Text(vorname), onTap: () => Navigator.pushNamed(context, PersonDetailsRoute, arguments: generatedPersons[index]));
76
+                    },
77
+                  )),
78
+            ),
79
+            Center(
80
+                child: RaisedButton(
81
+                    color: Colors.black,
82
+                    splashColor: Colors.blue,
83
+                    onPressed: !Network.isAvailable()
84
+                        ? null
85
+                        : () async {
86
+                            // 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}}}]';
87
+                            // var decoded = jsonDecode(jsondata);
88
+                            // Person p = Person(decoded[0]['firstname'], decoded[0]['lastname'], decoded[0]['age'], decoded[0]['gender']);
89
+                            // print(p);
90
+                            String firstname = "";
91
+                            await fetchPerson().then((value) async {
92
+                              if (value.isNotEmpty) {
93
+                                var json = jsonDecode(value)[0];
94
+                                Person p = Person(json['firstname'], json['lastname'], json['age'], json['gender']);
95
+                                SharedPreferences prefs = await _prefs;
96
+                                firstname = json['firstname'];
97
+
98
+                                setState(() {
99
+                                  generatedPersons.add(p);
100
+
101
+                                  List<String> personenliste = List<String>();
102
+
103
+                                  for (Person pobj in generatedPersons) {
104
+                                    print("Writing: ${pobj.toJson()}");
105
+                                    personenliste.add(pobj.toJson());
106
+                                  }
107
+
108
+                                  prefs.setStringList("Personenliste", personenliste);
109
+
110
+                                  listScrollController.jumpTo(listScrollController.position.maxScrollExtent);
111
+                                });
112
+                              }
113
+                            });
114
+
115
+                            SnackBar sb = SnackBar(content: Text("$firstname wurde angelegt."));
116
+
117
+                            AlertDialog alert = AlertDialog(
118
+                              title: Text("Neue Person"),
119
+                              content: Text("Es wurde eine neue Person angelegt: $firstname"),
120
+                              actions: [
121
+                                Column(
122
+                                  children: [
123
+                                    FlatButton(
124
+                                      child: Text("Ok"),
125
+                                      onPressed: () {
126
+                                        Navigator.of(context).pop();
127
+                                      },
128
+                                    ),
129
+                                    FlatButton(
130
+                                      child: Text("Cancel", style: TextStyle(color: Colors.red)),
131
+                                      onPressed: () {
132
+                                        Navigator.pop(context);
133
+                                      },
134
+                                    ),
135
+                                  ],
136
+                                )
137
+                              ],
138
+                            );
139
+
140
+                            // showDialog(context: context, builder: (context){
141
+                            //   return alert;
142
+                            // });
143
+
144
+                            // scaffoldKey.currentState.showSnackBar(sb);
145
+                            // var result = await Navigator.pushNamed(
146
+                            //     context, ZweiteSeiteRoute,
147
+                            //     arguments: 'Daten von der Startseite');
148
+                            // setState(() {
149
+                            //   empfangeneDaten = result;
150
+                            //   print(result);
151
+                            // });
152
+                          },
153
+                    child: Text("Gib mir einen Namen!", style: TextStyle(color: Colors.white)))),
154
+            Center(
155
+              child: RaisedButton(
156
+                  onPressed: () async {
157
+                    SharedPreferences prefs = await _prefs;
158
+                    setState(() {
159
+                      generatedPersons.clear();
160
+                      prefs.setStringList("Personenliste", List<String>());
161
+                    });
162
+                  },
163
+                  child: Text("Liste leeren")),
163 164
             ),
164 165
             Center(
165 166
               child: RaisedButton(
166
-                onPressed: () async {
167
-                  SharedPreferences prefs = await _prefs;
168
-                  setState(()  {
169
-                    generatedPersons.clear();
170
-                    prefs.setStringList("Personenliste", List<String>());
171
-                  });
172
-                },
173
-                child: Text("Liste leeren")
174
-              ),
167
+                  onPressed: () async {
168
+                    bool result = await Navigator.pushNamed(context, PersonHinzufuegenRoute);
169
+                    if (result) {
170
+                      setState(() {
171
+                        printPreferences();
172
+                      });
173
+                    }
174
+                  },
175
+                  child: Text("Person hinzufügen")),
175 176
             )
176
-
177
-      ],
178
-    )));
177
+          ],
178
+        )));
179 179
   }
180 180
 }

+ 39 - 0
lib/utils/network.dart

@@ -0,0 +1,39 @@
1
+import 'dart:async';
2
+import 'package:connectivity/connectivity.dart';
3
+
4
+class Network {
5
+  static bool _isAvailable = false;
6
+
7
+  static bool isAvailable() {
8
+    return _isAvailable;
9
+  }
10
+
11
+  static StreamSubscription<ConnectivityResult> _streamSubscription;
12
+
13
+  static Future<bool> isNetworkAvailable() async {
14
+    var connectivityResult = await Connectivity().checkConnectivity();
15
+    bool result = false;
16
+    if (connectivityResult != ConnectivityResult.none) {
17
+      result = true;
18
+    }
19
+    Network._isAvailable = result;
20
+    print("isAvailable: $_isAvailable");
21
+    return result;
22
+  }
23
+
24
+  static void init() async {
25
+    await isNetworkAvailable();
26
+
27
+    Network._streamSubscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) async {
28
+      print("Network changed!");
29
+      return await isNetworkAvailable();
30
+    });
31
+  }
32
+
33
+  static void registerSubscription(Function callback) {
34
+    StreamSubscription<ConnectivityResult> streamSubscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) async {
35
+      print("Network changed!");
36
+      callback();
37
+    });
38
+  }
39
+}

+ 28 - 0
pubspec.lock

@@ -43,6 +43,34 @@ packages:
43 43
       url: "https://pub.dartlang.org"
44 44
     source: hosted
45 45
     version: "1.15.0-nullsafety.3"
46
+  connectivity:
47
+    dependency: "direct main"
48
+    description:
49
+      name: connectivity
50
+      url: "https://pub.dartlang.org"
51
+    source: hosted
52
+    version: "0.4.9+5"
53
+  connectivity_for_web:
54
+    dependency: transitive
55
+    description:
56
+      name: connectivity_for_web
57
+      url: "https://pub.dartlang.org"
58
+    source: hosted
59
+    version: "0.3.1+2"
60
+  connectivity_macos:
61
+    dependency: transitive
62
+    description:
63
+      name: connectivity_macos
64
+      url: "https://pub.dartlang.org"
65
+    source: hosted
66
+    version: "0.1.0+5"
67
+  connectivity_platform_interface:
68
+    dependency: transitive
69
+    description:
70
+      name: connectivity_platform_interface
71
+      url: "https://pub.dartlang.org"
72
+    source: hosted
73
+    version: "1.0.6"
46 74
   cupertino_icons:
47 75
     dependency: "direct main"
48 76
     description:

+ 2 - 3
pubspec.yaml

@@ -3,7 +3,7 @@ description: A new Flutter project.
3 3
 
4 4
 # The following line prevents the package from being accidentally published to
5 5
 # pub.dev using `pub publish`. This is preferred for private packages.
6
-publish_to: 'none' # Remove this line if you wish to publish to pub.dev
6
+publish_to: "none" # Remove this line if you wish to publish to pub.dev
7 7
 
8 8
 # The following defines the version and build number for your application.
9 9
 # A version number is three numbers separated by dots, like 1.2.43
@@ -25,7 +25,7 @@ dependencies:
25 25
     sdk: flutter
26 26
   http: ^0.12.2
27 27
   shared_preferences: ^0.5.12
28
-
28
+  connectivity: ^0.4.9+5
29 29
 
30 30
   # The following adds the Cupertino Icons font to your application.
31 31
   # Use with the CupertinoIcons class for iOS style icons.
@@ -40,7 +40,6 @@ dev_dependencies:
40 40
 
41 41
 # The following section is specific to Flutter.
42 42
 flutter:
43
-
44 43
   # The following line ensures that the Material Icons font is
45 44
   # included with your application, so that you can use the icons in
46 45
   # the material Icons class.