Created
January 15, 2021 11:11
-
-
Save kotrotko/f72af73be2300fb14dff277ba6a9ae36 to your computer and use it in GitHub Desktop.
Send Data To Internet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'dart:convert'; | |
import 'package:flutter/material.dart'; | |
import 'package:http/http.dart' as http; | |
Future<User> createUser(String email) async { | |
final http.Response response = await http.post( | |
'http://10.0.11.157:8000/api/user', | |
headers: <String, String>{ | |
'Content-Type': 'application/json; charset=UTF-8', | |
}, | |
body: jsonEncode(<String, String>{ | |
'email': email, | |
}), | |
); | |
if (response.statusCode == 201) { | |
return User.fromJson(jsonDecode(response.body)); | |
} else { | |
throw Exception('Failed to create user.'); | |
} | |
} | |
class User { | |
final String email; | |
final String password; | |
User({this.email, this.password}); | |
factory User.fromJson(Map<String, dynamic> json) { | |
return User( | |
email: json['email'], | |
password: json['password'], | |
); | |
} | |
} | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatefulWidget { | |
MyApp({Key key}) : super(key: key); | |
@override | |
_MyAppState createState() { | |
return _MyAppState(); | |
} | |
} | |
class _MyAppState extends State<MyApp> { | |
final TextEditingController _controller = TextEditingController(); | |
Future<User> _futureUser; | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Create Data Example', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: Scaffold( | |
appBar: AppBar( | |
title: Text('Create Data Example'), | |
), | |
body: Container( | |
alignment: Alignment.center, | |
padding: const EdgeInsets.all(8.0), | |
child: (_futureUser == null) | |
? Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
TextField( | |
controller: _controller, | |
decoration: InputDecoration(hintText: 'Enter Title'), | |
), | |
RaisedButton( | |
child: Text('Create Data'), | |
onPressed: () { | |
setState(() { | |
_futureUser = createUser(_controller.text); | |
}); | |
}, | |
), | |
], | |
) | |
: FutureBuilder<User>( | |
future: _futureUser, | |
builder: (context, snapshot) { | |
if (snapshot.hasData) { | |
return Text(snapshot.data.email); | |
} else if (snapshot.hasError) { | |
return Text("${snapshot.error}"); | |
} | |
return CircularProgressIndicator(); | |
}, | |
), | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment