Flutter: How to make a login in flutter - authentication

[![Here is the button that the users will click][1]][1] How can I make and display a login form this is what I'm trying to do.
after a user clicked on the first button.
This is where I want to put the Login Form in the class SecondScreen.Also, I want to learn how to make a simple login form in Flutter
class SecondScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [Colors.amberAccent, Colors.red]),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center, // add Column
children: <Widget>[
Text('Welcome2',
style: TextStyle(
// your text
fontSize: 50.0,
fontWeight: FontWeight.bold,
color: Colors.white)),
RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Button'),
shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0)),
color: Colors.white,
splashColor: Colors.blue,
textColor: Color(0xfffe67e22),
), // your button beneath text
],
),
),
),
);
}
}

For simple login form you you can do like this,
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_app_stack/color_utils.dart';
import 'package:flutter_app_stack/common_styles.dart';
import 'package:flutter_app_stack/raised_gradient_button.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(
primarySwatch: Colors.blue,
),
home: LoginScreen(),
);
}
}
class LoginScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _LoginScreenState();
}
}
class _LoginScreenState extends State<LoginScreen> {
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height,
child: Stack(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height * 0.40,
width: double.infinity,
decoration: BoxDecoration(gradient: ColorUtils.appBarGradient),
),
Align(
alignment: Alignment.topCenter,
child: Padding(
padding: const EdgeInsets.only(top: 80),
child: Text(
"Login",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w800,
fontSize: 19),
),
)),
Positioned(
top: 150,
left: 10,
right: 10,
child: LoginFormWidget(),
)
],
),
),
),
);
}
}
class LoginFormWidget extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _LoginFormWidgetState();
}
}
class _LoginFormWidgetState extends State<LoginFormWidget> {
final _formKey = GlobalKey<FormState>();
var _userEmailController = TextEditingController(text: "jm1#example.com");
var _userPasswordController = TextEditingController(text: "jay#123");
var _emailFocusNode = FocusNode();
var _passwordFocusNode = FocusNode();
bool _isPasswordVisible = true;
bool _autoValidate = false;
#override
Widget build(BuildContext context) {
return Form(
key: _formKey,
autovalidate: _autoValidate,
child: Column(
children: <Widget>[
Card(
elevation: 8,
child: Column(
children: <Widget>[
_buildLogo(),
_buildIntroText(),
_buildEmailField(context),
_buildPasswordField(context),
_buildForgotPasswordWidget(context),
_buildSignUpButton(context),
_buildLoginOptionText(),
_buildSocialLoginRow(context),
],
),
),
_buildSignUp(),
],
),
);
}
Widget _buildSocialLoginRow(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(right: 20, left: 20, bottom: 20),
child: Row(
children: <Widget>[
__buildFacebookButtonWidget(context),
__buildTwitterButtonWidget(context)
],
),
);
}
Widget __buildTwitterButtonWidget(BuildContext context) {
return Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: RaisedButton(
color: Color.fromRGBO(29, 161, 242, 1.0),
child: Image.asset(
"assets/images/ic_twitter.png",
width: 25,
height: 25,
),
onPressed: () {},
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0))),
),
);
}
Widget __buildFacebookButtonWidget(BuildContext context) {
return Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: RaisedButton(
color: Color.fromRGBO(42, 82, 151, 1.0),
child: Image.asset(
"assets/images/ic_fb.png",
width: 35,
height: 35,
),
onPressed: () {},
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0))),
),
);
}
Widget _buildLoginOptionText() {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Text(
"Or sign up with social account",
style: TextStyle(
fontSize: 14, color: Colors.black54, fontWeight: FontWeight.w600),
),
);
}
Widget _buildIntroText() {
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 5, bottom: 30),
child: Text(
"My Recipes",
style: TextStyle(
color: Colors.black54,
fontSize: 18.0,
fontWeight: FontWeight.bold),
),
),
],
);
}
Widget _buildLogo() {
return Padding(
padding: const EdgeInsets.only(top: 10),
child: Image.asset(
"assets/images/ic_launcher.png",
height: 100,
width: 100,
),
);
}
String _userNameValidation(String value) {
if (value.isEmpty) {
return "Please enter valid user name";
} else {
return null;
}
}
Widget _buildEmailField(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 5),
child: TextFormField(
controller: _userEmailController,
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) {
FocusScope.of(context).requestFocus(_passwordFocusNode);
},
validator: (value) => _emailValidation(value),
decoration: CommonStyles.textFormFieldStyle("Email", ""),
),
);
}
String _emailValidation(String value) {
bool emailValid =
RegExp(r"^[a-zA-Z0-9.]+#[a-zA-Z0-9]+\.[a-zA-Z]+").hasMatch(value);
if (!emailValid) {
return "Enter valid email address";
} else {
return null;
}
}
Widget _buildPasswordField(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 5),
child: TextFormField(
controller: _userPasswordController,
keyboardType: TextInputType.text,
textInputAction: TextInputAction.next,
onFieldSubmitted: (_) {
FocusScope.of(context).requestFocus(_emailFocusNode);
},
validator: (value) => _userNameValidation(value),
obscureText: _isPasswordVisible,
decoration: InputDecoration(
labelText: "Password",
hintText: "",
labelStyle: TextStyle(color: Colors.black),
alignLabelWithHint: true,
contentPadding: EdgeInsets.symmetric(vertical: 5),
suffixIcon: IconButton(
icon: Icon(
_isPasswordVisible ? Icons.visibility_off : Icons.visibility,
color: Colors.black,
),
onPressed: () {
setState(() {
_isPasswordVisible = !_isPasswordVisible;
});
}),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.black,
),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 2),
),
),
),
);
}
Widget _buildForgotPasswordWidget(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 10.0),
child: Align(
alignment: Alignment.centerRight,
child: FlatButton(
onPressed: () {},
child: Text(
'Forgot your password ?',
style:
TextStyle(color: Colors.black54, fontWeight: FontWeight.w500),
)),
),
);
}
Widget _buildSignUpButton(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0),
child: Container(
padding: EdgeInsets.symmetric(horizontal: 15.0),
width: double.infinity,
child: RaisedGradientButton(
child: Text(
"Login",
style: TextStyle(
color: Colors.white, fontSize: 18, fontWeight: FontWeight.w600),
),
onPressed: () {
_signUpProcess(context);
},
),
),
);
}
void _signUpProcess(BuildContext context) {
var validate = _formKey.currentState.validate();
if (validate) {
//Do login stuff
} else {
setState(() {
_autoValidate = true;
});
}
}
void _clearAllFields() {
setState(() {
_userEmailController = TextEditingController(text: "");
_userPasswordController = TextEditingController(text: "");
});
}
Widget _buildSignUp() {
return Padding(
padding: const EdgeInsets.only(top: 15),
child: RichText(
text: TextSpan(
style: DefaultTextStyle.of(context).style,
children: <TextSpan>[
TextSpan(
text: "Don't have an Account ? ",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
),
TextSpan(
text: 'Register',
style: TextStyle(
fontWeight: FontWeight.w800,
color: Colors.orange,
fontSize: 14),
),
],
),
),
);
}
}
color_utils.dart
import 'package:flutter/material.dart';
class ColorUtils {
static const Color primaryColor = Color(0xffEC9F05);
static const Color accentColor = Color(0xffFF4E00);
static const Color orangeGradientEnd = Color(0xfffc4a1a);
static const Color orangeGradientStart = Color(0xfff7b733);
static const Color themeGradientStart = Color(0xFF8E24AA);
static const Color themeGradientEnd = Color(0xFFFB8C00);
static const LinearGradient appBarGradient =
LinearGradient(colors: [themeGradientStart, themeGradientEnd]);
}
common_styles.dart
import 'package:flutter/material.dart';
class CommonStyles {
static textFormFieldStyle(String label, String hint) {
return InputDecoration(
labelText: label,
hintText: hint,
alignLabelWithHint:true,
contentPadding: EdgeInsets.symmetric(vertical: 5),
labelStyle: TextStyle(color: Colors.black),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.black,
),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.black,
width: 2
),
),
);
}
}
raised_gradient_button.dart
import 'package:flutter/material.dart';
import 'package:flutter_app_stack/color_utils.dart';
class RaisedGradientButton extends StatelessWidget {
final Widget child;
final double width;
final double height;
final Function onPressed;
RaisedGradientButton({
Key key,
#required this.child,
this.width = double.infinity,
this.height = 40.0,
this.onPressed,
}) : super(key: key);
#override
Widget build(BuildContext context) {
Gradient _gradient = LinearGradient(
colors: [ColorUtils.themeGradientStart, ColorUtils.themeGradientEnd]);
return Container(
width: width,
height: height,
decoration: BoxDecoration(
borderRadius: new BorderRadius.all(Radius.circular(40.0)),
gradient: _gradient,
boxShadow: [
BoxShadow(
color: Colors.grey[500],
offset: Offset(0.0, 1.5),
blurRadius: 1.5,
),
]),
child: Material(
color: Colors.transparent,
child: InkWell(
borderRadius: new BorderRadius.all(Radius.circular(40.0)),
onTap: onPressed,
child: Center(
child: child,
)),
),
);
}
}

Simple Login page With Password Username Validation
import 'package:flutter/material.dart';
import 'SignUp.dart';
import 'Home.dart';
import 'package:fluttertoast/fluttertoast.dart';
class LoginScreen extends StatefulWidget {
#override
_Login createState() => _Login();
}
final unameController = TextEditingController();
final passController = TextEditingController();
String uname = "uname";
String pass = "pass";
class _Login extends State<LoginScreen> {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "Smple Login",
home: Scaffold(
resizeToAvoidBottomPadding: false,
body: Center(
child: Container(
height: 400,
width: 300,
child: Column(
children: [
Text("Login Here"),
TextField(
controller: unameController,
decoration: InputDecoration(
prefixIcon: Icon(Icons.mobile_friendly,),
hintText: "Username",
),
),
TextField(
controller: passController,
decoration: InputDecoration(
prefixIcon: Icon(Icons.keyboard,),
hintText: "PassWord",
),
),
Container(
alignment: Alignment.centerRight,
child: GestureDetector(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => SignUp()));
},
child: Text("Create Account?"),
)),
ElevatedButton(
child: Text("Submit"),
onPressed: () {
if (uname == unameController.text &&
pass == passController.text) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
Home(username: "Hello World from Login")));
} else {
Fluttertoast.showToast(
msg: "Invalid Username or Password");
unameController.text="";
passController.text="";
}
},
),
],
),
),
),
),
);
}
}

Related

Flutter API Data fetch

How to bind my json response to my project ? Can you show me how to convert this data on this site? but i got error
Tried calling: map(Clouser:(Dynamic)=> CampaignSHelList)
Here is my json response:
{
"Success": {
"SuccessCode": "S0019",
"SuccessMessage": "Success.",
"CompaignShelfList": [
{
"CoverImagePath": "https://photogranthtest.s3.ap-south-1.amazonaws.com/uploads/default/images/default_cover.png",
"ShelfImagePath": "https://photogranthtest.s3.ap-south-1.amazonaws.com/uploads/photographerCampaign/3/shelfImage/3_shelfimage.jpg",
"CampaignTitle": "Brithday",
"Date": "28/11/2020",
"BusinessName": "Wedding Photographer1",
"PhotographerEmail": "pratap#gmail.com",
"PhotographerImageLogo": "",
"PhotographerMobileNumber": "8484007598",
"PhotographerFullName": "Pratap Adhav",
"PhotographerWebsite": "https://www.google.com",
"PhotographerProfilePhoto": "https://photogranthtest.s3.ap-south-1.amazonaws.com/uploads/photographer/6/profile/bob_6731.jpg",
"PhotographerCampaignId": 3
},
{
"CoverImagePath": "https://photogranthtest.s3.ap-south-1.amazonaws.com/uploads/photographerCampaign/2/coverImage/_coverimage_htc-desire-620g-ds-400x400-imae2zgszqyfk2vx.jpeg",
"ShelfImagePath": "https://photogranthtest.s3.ap-south-1.amazonaws.com/uploads/photographerCampaign/2/shelfImage/2_shelfimage.jpg",
"CampaignTitle": "Sunil weds Sunita",
"Date": "14/02/2021",
"BusinessName": "Wedding Photographer1",
"PhotographerEmail": "pratap#gmail.com",
"PhotographerImageLogo": "",
"PhotographerMobileNumber": "8484007598",
"PhotographerFullName": "Pratap Adhav",
"PhotographerWebsite": "https://www.google.com",
"PhotographerProfilePhoto": "https://photogranthtest.s3.ap-south-1.amazonaws.com/uploads/photographer/6/profile/bob_6731.jpg",
"PhotographerCampaignId": 2
}
]
}
}
This is my ShelfScreen class:
import 'package:flutter/material.dart';
import 'dart:ui';
import 'dart:convert';
import 'data/shelfscreendata.dart';
import 'package:google_fonts/google_fonts.dart';
import 'constant/constant.dart' as Constants;
import 'PhotographerWelcomeNote.dart';
import 'package:http/http.dart' as http;
import 'Utility/global.dart' as Globals;
import 'data/errordata.dart';
import 'data/shelfscreendata.dart';
import 'data/shelfscreendata.dart';
class ShelfScreen extends StatefulWidget {
#override
_ShelfScreenState createState() => _ShelfScreenState();
}
class _ShelfScreenState extends State<ShelfScreen> {
Future<Success> _futureShelf;
Future<Success> Shelf() async {
Map data = {
"AccessToken": "MjUyLTg1REEyUzMtQURTUzVELUVJNUI0QTIyMTE=",
"CustomerId": 1
};
final http.Response response = await http.post(
"http://api.pgapp.in/v1/shelflist",
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(data),
);
if (response.statusCode == 200) {
// If the server did return a 201 CREATED response,
// then parse the JSON.
return Success.fromJson(json.decode(response.body));
} else {
// If the server did not return a 201 CREATED response,
// then throw an exception.
throw Exception('Failed to load data');
}
}
#override
void initState() {
super.initState();
_futureShelf = Shelf();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: const Color(0xfff8f8f8),
leading: Padding(
padding: EdgeInsets.only(left: 20),
child: Image.asset("assets/logo.png",width: 45,height: 45,),
),
title: Center(
child: Image.asset("assets/Textimage.png",width: 170,height: 45),
),
actions: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 20,top: 10,bottom: 10),
child: Container(
height: 8,
width: 35,
child: CircleAvatar(
maxRadius: 20,
backgroundImage: AssetImage("assets/images/prof.jpg"),
),
),
),
],
),
body: (_futureShelf == null)
? Text("No Data found")
: FutureBuilder<Success>(
future: _futureShelf,
builder: (context, snapshot) {
if (snapshot.hasData) {
if (snapshot.data.hasError) {
return Center(
child: Text("${snapshot.data.Error.ErrorMessage}"));
} else {
if (snapshot.data.compaignShelfList.length > 0) {
return gridimages(
items: snapshot.data.compaignShelfList,
);
} else {
return Center(child: Text("No Data found"));
}
}
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Center(child: CircularProgressIndicator());
},
)
);
}
}
class gridimages extends StatelessWidget {
final List<CompaignShelfList> items;
gridimages({Key key, this.items});
#override
Widget build(BuildContext context) {
return
GridView.builder(
shrinkWrap: false,
scrollDirection: Axis.vertical,
gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 1,
childAspectRatio: 1.200,
mainAxisSpacing: 1.0,
crossAxisSpacing: 1.0,
),
itemCount: items.length,
itemBuilder: (context, int index){
return CategoriesTile(
imgUrls: items[index].coverImagePath,
catagory:items[index].businessName,
date: items[index].date,
email: items[index].photographerEmail,
stduio:items[index].businessName,
);
// Image.asset(Shelflist[index]["text_3"],fit: BoxFit.cover,);
}
);
}
}
class CategoriesTile extends StatelessWidget {
final String imgUrls, catagory , date,email,stduio;
CategoriesTile({#required this.imgUrls, #required this.catagory,#required this.date,#required
this.email,#required this.stduio});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PhotographerWelcomeNote(
Coverpic: imgUrls,
)));
},
child: Card(
semanticContainer: true,
clipBehavior: Clip.antiAliasWithSaveLayer,
elevation: 5,
child: Container(
margin: EdgeInsets.all(8),
child:
Stack(
children: <Widget>[
Positioned(
top: 1,
left: 1,
right: 1,
bottom: 50,
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child:Image.asset(
imgUrls,
height: 250,
width: 400,
fit: BoxFit.cover,
)
),
),
Positioned(
bottom: 50,
left: 1,
right: 1,
// width: 400,
height: 60,
child: ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 3, sigmaY: 3),
child: Container(
decoration: BoxDecoration(
color: Colors.black.withOpacity(0),
borderRadius: BorderRadius.circular(8),
),
),
),
),
),
Positioned(
bottom: 80,
left: 20,
child: Container(
height: 50,
width: 400,
alignment: Alignment.bottomLeft,
child: Text(
catagory ?? "Yo Yo",
style: GoogleFonts.nunito(
fontSize: 18,
color: const Color(0xffffffff),
fontWeight: FontWeight.w700,
height: 1.7647058823529411,
),
)),
),
Positioned(
left: 20,
bottom: 60,
child: Container(
height: 30,
width: 150,
alignment: Alignment.bottomLeft,
child: Text(
date,style: GoogleFonts.nunito(
fontSize: 13,
color: const Color(0xffffffff),
fontWeight: FontWeight.w700,
height: 1.7647058823529411,
),
),
),
),
Positioned(
bottom: 20,
left: 90,
child: Container(
height: 23,
alignment: Alignment.center,
child: Text(
stduio,
style: GoogleFonts.nunito(
fontSize: 18,
color: const Color(0xff7f7f7f),
fontWeight: FontWeight.w700,
)
),
),
),
Positioned(
bottom: 1,
left: 90,
child: Container(
height: 20,
alignment: Alignment.center,
child: Text(
email,style: GoogleFonts.nunito(
fontSize: 10,
color: const Color(0xffb4b4b4),
fontWeight: FontWeight.w600,
),
),
),
),
Positioned(
bottom: 2,
left: 10,
child: Container(
width: 66.0,
height: 39.0,
decoration: BoxDecoration(
image: DecorationImage(
image: const AssetImage(
'assets/images/camlogo.jpg'),
fit: BoxFit.cover,
),
border: Border.all(
width: 1.0, color: const Color(0xffb4b4b4)),
),
),
),
],
),
),
),
);
}
}

setState() called in constructor: _WeatherState#823a5(lifecycle state: created, no widget, not mounted) error flutter

weather api page
please help me I have a problem in code, I want to change myURL variable from mycity variable, I have a set of city how I can do that :
Editor Error : setState() called in constructor: _WeatherState#823a5(lifecycle state: created, no widget, not mounted)
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:marwa_app/component/myResponsiveLibrary.dart';
import 'package:marwa_app/component/Logo.dart';
import 'package:marwa_app/component/MyDrawer.dart';
import 'package:http/http.dart' as http;
class Weather extends StatefulWidget {
#override
_WeatherState createState() => _WeatherState();
}
class _WeatherState extends State<Weather> {
List <String> mycity = ['aqaba','amman'];
int i= 0;
void cityValue(value) {
setState(() {
i = value;
});
}
#override
Future<Map> getData() async{
String myURL = await 'http://api.openweathermap.org/data/2.5/forecast?q=${mycity[i]}&appid=41a6cd80a840ce00a3c77b8ba1a04022&units=metric';
http.Response response = await http.get(myURL);
return json.decode(response.body);
}
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: MainModel().mainColor,
appBar: AppBar(
backgroundColor: Color(0xff323266),
leading: IconButton(
icon: Icon(
Icons.notifications_active,
color: MainModel().thirdColor,
),
onPressed: () => {}),
title: Logo(),
centerTitle: true,
actions: [
Builder(
builder: (context) => IconButton(
icon: Icon(
Icons.menu,
color: MainModel().thirdColor,
),
onPressed: () => Scaffold.of(context).openEndDrawer(),
tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
),
),
],
),
endDrawer: Drawer(
child: MyDrawer(),
),
body: widgetMyData()
);
}
}
Widget widgetMyData() {
return FutureBuilder(future: _WeatherState().getData(),
builder: (BuildContext context, AsyncSnapshot<Map> snapshop){
final widthScreen = MediaQuery.of(context).size.width;
if(snapshop.hasData){
Map content = snapshop.data;
return Container(
color: MainModel().secondColor,
child: Center(
child: ListView(
physics: NeverScrollableScrollPhysics(),
children: [
Padding(padding: EdgeInsets.only(top: 20)),
Container(
margin: EdgeInsets.symmetric(horizontal: MainModel().setPadding(MainModel().largePadding, widthScreen)),
height: 300,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.15),
spreadRadius: 5,
blurRadius: 5,
offset: Offset(2, 2), // changes position of shadow
),],
borderRadius: BorderRadius.all(Radius.circular(40)),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
MainModel().mainColor, MainModel().secondColor
])
),
child: Column(
children: [
Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().smallPadding, widthScreen)),),
Image.network('http://openweathermap.org/img/w/${content["list"][0]["weather"][0]["icon"]}.png',
color: MainModel().whiteColor.withOpacity(0.7),
fit: BoxFit.contain,
width: 120,),
Text('${content['list'][0]['weather'][0]['description']}',style: TextStyle(
fontSize: MainModel().setFont(MainModel().middleFont, widthScreen),
color: MainModel().whiteColor.withOpacity(0.7),
),),
Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding * 1.5, widthScreen)),),
Text("${content['list'][0]['main']['temp']}\u00b0C",
style: TextStyle(
fontSize: MainModel().setFont(MainModel().largeFont * 1.5, widthScreen),
color: MainModel().whiteColor,
fontWeight: FontWeight.bold
),),
Container(
alignment: Alignment.center,
child: Text("${content['city']['name']}",style: TextStyle(
fontSize: MainModel().setFont(MainModel().middleFont, widthScreen),
color: MainModel().whiteColor,
),)
),
Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding * 1.5, widthScreen)),),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text("${content['list'][0]['main']['temp_max']}\u00b0C",style: TextStyle(
fontSize: MainModel().setFont(MainModel().middleFont, widthScreen),
color: MainModel().whiteColor,
fontWeight: FontWeight.bold
),),
Text("${content['list'][0]['main']['temp_min']}\u00b0C",style: TextStyle(
fontSize: MainModel().setFont(MainModel().middleFont, widthScreen),
color: MainModel().whiteColor,
fontWeight: FontWeight.bold
),),
],
),
],
),
),
Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding * 2, widthScreen))),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
Padding(padding: EdgeInsets.only(left: MainModel().setPadding(MainModel().middlePadding, widthScreen))),
Container(
height: MainModel().setSize(MainModel().largeSize, widthScreen),
width: MainModel().setSize(MainModel().largeSize, widthScreen),
decoration: BoxDecoration(
color: Color(0xffFFB20F),
borderRadius: BorderRadius.all(Radius.circular(40.0)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding, widthScreen))),
],
)
),
Padding(padding: EdgeInsets.only(left: MainModel().setPadding(MainModel().middlePadding, widthScreen))),
Container(
height: MainModel().setSize(MainModel().largeSize, widthScreen),
width: MainModel().setSize(MainModel().largeSize, widthScreen),
decoration: BoxDecoration(
color: Color(0xff0DA6A6),
borderRadius: BorderRadius.all(Radius.circular(40.0)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding, widthScreen))),
],
)
),
Padding(padding: EdgeInsets.only(left: MainModel().setPadding(MainModel().middlePadding, widthScreen))),
Container(
height: MainModel().setSize(MainModel().largeSize, widthScreen),
width: MainModel().setSize(MainModel().largeSize, widthScreen),
decoration: BoxDecoration(
color: Color(0xff6D5DF1),
borderRadius: BorderRadius.all(Radius.circular(40.0)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding, widthScreen))),
],
)
),
Padding(padding: EdgeInsets.only(left: MainModel().setPadding(MainModel().middlePadding, widthScreen))),
FlatButton(onPressed: () {
_WeatherState().cityValue(1);
},
child: Container(
height: MainModel().setSize(MainModel().largeSize, widthScreen),
width: MainModel().setSize(MainModel().largeSize, widthScreen),
decoration: BoxDecoration(
color: Color(0xffFF0F97),
borderRadius: BorderRadius.all(Radius.circular(40.0)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text('click'),
Padding(padding: EdgeInsets.only(top: MainModel().setPadding(MainModel().largePadding, widthScreen))),
],
)
),
),
Padding(padding: EdgeInsets.only(left: MainModel().setPadding(MainModel().middlePadding, widthScreen))),
],
))
]),
),
);
}else{
return Container(
child: Text('sorry you data is not found'),
);
}
}
);
}
if click in _WeatherState().cityValue(1);
change api city name
You can copy paste run full code below
You can pass getData() and cityValue to widgetMyData(Future<Map> _future, Function callback)
code snippet
Future<Map> _future;
...
#override
initState() {
_future = getData();
super.initState();
}
...
body: widgetMyData(_future, cityValue));
...
Widget widgetMyData(Future<Map> _future, Function callback) {
return FutureBuilder(
future: _future,
...
FlatButton(
onPressed: () {
callback(1);
},
child: Text('click'))
working demo
full code
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
class Weather extends StatefulWidget {
#override
_WeatherState createState() => _WeatherState();
}
class _WeatherState extends State<Weather> {
List<String> mycity = ['aqaba', 'amman'];
int i = 0;
Future<Map> _future;
void cityValue(value) {
setState(() {
i = value;
_future = getData();
});
}
#override
initState() {
_future = getData();
super.initState();
}
Future<Map> getData() async {
String myURL =
await 'https://api.openweathermap.org/data/2.5/forecast?q=${mycity[i]}&appid=41a6cd80a840ce00a3c77b8ba1a04022&units=metric';
http.Response response = await http.get(myURL);
return json.decode(response.body);
}
#override
Widget build(BuildContext context) {
return Scaffold(
//backgroundColor: MainModel().mainColor,
appBar: AppBar(
backgroundColor: Color(0xff323266),
leading: IconButton(
icon: Icon(
Icons.notifications_active,
//color: MainModel().thirdColor,
),
onPressed: () => {}),
title: Text("Logo()"),
centerTitle: true,
actions: [
Builder(
builder: (context) => IconButton(
icon: Icon(
Icons.menu,
//color: MainModel().thirdColor,
),
onPressed: () => Scaffold.of(context).openEndDrawer(),
tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
),
),
],
),
body: widgetMyData(_future, cityValue));
}
}
Widget widgetMyData(Future<Map> _future, Function callback) {
return FutureBuilder(
future: _future,
builder: (BuildContext context, AsyncSnapshot<Map> snapshop) {
final widthScreen = MediaQuery.of(context).size.width;
if (snapshop.hasData) {
Map content = snapshop.data;
return Container(
child: Center(
child:
ListView(physics: NeverScrollableScrollPhysics(), children: [
Padding(padding: EdgeInsets.only(top: 20)),
Container(
height: 300,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.15),
spreadRadius: 5,
blurRadius: 5,
offset: Offset(2, 2), // changes position of shadow
),
],
borderRadius: BorderRadius.all(Radius.circular(40)),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Colors.blue, Colors.red])),
child: Column(
children: [
Image.network(
'https://openweathermap.org/img/w/${content["list"][0]["weather"][0]["icon"]}.png',
//color: MainModel().whiteColor.withOpacity(0.7),
fit: BoxFit.contain,
width: 120,
),
Text(
'${content['list'][0]['weather'][0]['description']}',
),
Text(
"${content['list'][0]['main']['temp']}\u00b0C",
),
Container(
alignment: Alignment.center,
child: Text(
"${content['city']['name']}",
)),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(
"${content['list'][0]['main']['temp_max']}\u00b0C",
),
Text(
"${content['list'][0]['main']['temp_min']}\u00b0C",
),
],
),
],
),
),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
FlatButton(
onPressed: () {
callback(1);
},
child: Text('click')),
],
))
]),
),
);
} else {
return Container(
child: Text('sorry you data is not found'),
);
}
});
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Weather(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Flutter - Twitter API - Tweets not in correct order

I am currently in the process of programming an app in Flutter in which I will also integrate a Twitter feed with the Twitter API. I use the plugin
twitter_api: ^ 0.1.2
to query the twitter api. In the tweets, I also include a link preview in my app via a separate api on my virtual server. I currently have the problem that the tweets are displayed in the wrong order. my assumption is that it is because the http requests of the link preview take different lengths of time and therefore the problem arises that the widgets that are built first are then displayed first. I've already tried to slow down the loop with
await Future.delay(Duration(seconds: 1));
but unfortunately it didn't work either. I would be very grateful for any advice. here is my source code for the twitter feed:
void getTwitterFeed(String userID) async {
Future twitterUserRequest = _twitterOauth.getTwitterRequest(
"GET",
"users/show.json",
options: {
"user_id": userID,
}
);
var userRes = await twitterUserRequest;
var user = json.decode(userRes.body);
String profileIMGTMP = user["profile_image_url_https"];
String profileIMGTmp = profileIMGTMP.replaceAll('_normal', '');
User tmpUser = new User(name: user['name'], screeName: '#' + user['screen_name'], profileImageURL: profileIMGTmp);
Future twitterFeedRequest = _twitterOauth.getTwitterRequest(
"GET",
"statuses/user_timeline.json",
options: {
"user_id": "18641554",
"trim_user": "false",
"tweet_mode": "extended",
"count": "20",
}
);
var feedRes = await twitterFeedRequest;
var profile = json.decode(feedRes.body);
List<Tweet> tmpTweetList = [];
for (var tweet in profile) {
URLS tmpURLS = new URLS(tweet["entities"]["urls"][0]["url"], tweet["entities"]["urls"][0]["expanded_url"], tweet["entities"]["urls"][0]["display_url"],);
Tweet tmpTweet = new Tweet(user: tweet["user"]["id_str"], createdAt: tweet["created_at"], timeAgo: timeago.format(parseDateTime(tweet["created_at"]), locale: 'de'), fullText: tweet["full_text"], urls: tmpURLS);
tmpTweetList.add(tmpTweet);
}
List<Widget> tmpTweetWidgetList = [];
tmpTweetList.forEach((t) async {
await Future.delayed(Duration(seconds: 3));
String tmpFullText = t.fullText.replaceAll(t.urls.url, '');
var metaRequest = await http.get('https://api.aw96.de/dbna/?url=' + t.urls.url);
var metaResponse = json.decode(metaRequest.body);
String image = metaResponse['image'];
if (image.isEmpty) {
setState(() {
image = 'https://icon-library.com/images/no-image-available-icon/no-image-available-icon-6.jpg';
});
}
tmpTweetWidgetList.add(
Padding(
padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
child: Container(
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
color: Colors.transparent,
border: Border.all(color: Color.fromRGBO(104, 114, 124, 1)),
borderRadius: BorderRadius.circular(8.0),
),
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(50),
child: Image.network(
tmpUser.profileImageURL,
width: 35,
height: 35,
),
),
SizedBox(
width: 10.0,
),
Text(
tmpUser.name,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 18.0,
),
),
SizedBox(
width: 10.0,
),
Text(
tmpUser.screeName,
style: TextStyle(
color: Color.fromRGBO(104, 114, 124, 1),
fontWeight: FontWeight.bold,
fontSize: 14.0,
),
),
SizedBox(
width: 10.0,
),
Text(
t.timeAgo,
style: TextStyle(
color: Color.fromRGBO(104, 114, 124, 1),
fontWeight: FontWeight.bold,
fontSize: 14.0,
),
),
],
),
Padding(
padding: EdgeInsets.only(top: 15, left: 48, bottom: 10),
child: Column(
children: [
Text(
tmpFullText,
style: TextStyle(
color: Colors.white,
fontSize: 18,
),
),
SizedBox(
height: 15.0,
),
Container(
child: GestureDetector(
onTap: () async {
await launch(t.urls.url);
},
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Color.fromRGBO(104, 114, 124, 1)),
borderRadius: BorderRadius.circular(8.0),
),
child: Column(
children: [
Image.network(
image
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 15.0),
child: Text(
metaResponse['title'],
style: TextStyle(
color: Colors.white,
fontSize: 18,
),
),
),
],
),
),
),
),
],
),
),
],
),
),
),
),
);
});
setState(() {
tweets = tmpTweetWidgetList;
});
}
Hopefully you can help me with that. Best regards from Germany

Flutter make chat screen there message fetch or send in api

I have 2 problems here.
when i type a message in textfield than close the keyboard without send message written text automatically erase.
I don't get real time message from api when reload the screen than after i get all messages. I want send or receive messages in real time.
Note: I use the two api for send messages AND receive messages. For send messages api call on send button click.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:application1/modals/msgdisplay.dart';
import 'package:application1/modals/msgsend.dart';
import 'package:application1/services/api.dart';
import 'package:application1/widgets/bottombar.dart';
import 'package:application1/widgets/sizeconfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'package:web_socket_channel/web_socket_channel.dart';
// ignore: must_be_immutable
class PersonalChat1 extends StatefulWidget {
String userid, username, userphoto;
PersonalChat1(this.userid, this.username, this.userphoto, {Key key})
: super(key: key);
#override
_PersonalChat1State createState() => _PersonalChat1State();
}
Future<String> getNamePreference() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String id = prefs.getString("id");
return id;
}
Future<Msgsend> msgSend(String regid, String userid, String sid, String msgtext,
String msgimage) async {
final String apiUrl = url + 'msg_insert.php';
final response = await http.post(apiUrl, headers: {
'Accept': 'application/json'
}, body: {
"regid": regid,
"user_id": userid,
"subcategory_id": sid,
"msg_text": msgtext,
"msg_image": msgimage,
});
print(response.statusCode);
if (response.statusCode == 200) {
final String responseString = response.body;
print(responseString);
return msgsendFromJson(responseString);
} else {
return null;
}
}
List<MsgDisplay> _msgLists = List<MsgDisplay>();
Future<List<MsgDisplay>> msgList(String regid, String uid, String sid) async {
final String apiUrl = url + 'display_msg.php';
final response = await http.post(apiUrl, headers: {
'Accept': 'application/json'
}, body: {
"regid": regid,
"uid": uid,
"sid": sid,
});
var msgList = List<MsgDisplay>();
// print(response.statusCode);
if (response.statusCode == 200) {
var responseString = json.decode(response.body);
print(responseString);
for (var user in responseString["server"]) {
msgList.add(MsgDisplay.fromJson(user));
}
} else {
return null;
}
return msgList;
}
class _PersonalChat1State extends State<PersonalChat1> {
String _id = '';
// Timer timer;
#override
void initState() {
super.initState();
getNamePreference().then((String id) {
setState(() {
this._id = id;
});
msgList(_id, widget.userid, "0").then((value) {
setState(() {
_msgLists.clear();
_msgLists.addAll(value);
});
});
// timer = Timer.periodic(
// Duration(seconds: 1),
// (Timer t) => addValue(),
// );
print(_id);
});
}
// void addValue() {
// setState(() {
// msgList(_id, widget.userid, "0").then((value) {
// _msgLists.clear();
// _msgLists.addAll(value);
// });
// });
// }
// setUpTimedFetch() async {
// Timer.periodic(Duration(seconds: 1), (timer) {
// msgList(_id, widget.userid, "0").then((value) {
// setState(() {
// _msgLists.clear();
// _msgLists.addAll(value);
// });
// });
// });
// }
// #override
// void dispose() {
// timer?.cancel();
// super.dispose();
// }
#override
Widget build(BuildContext context) {
final FocusNode _msgFocus = FocusNode();
TextEditingController _msg = TextEditingController();
ScrollController _scrollController = ScrollController();
final GlobalKey<FormState> _formkey = GlobalKey<FormState>();
SizeConfig().init(context);
File _image;
final picker = ImagePicker();
// Size size = MediaQuery.of(context).size;
return WillPopScope(
onWillPop: () async {
Navigator.of(context).pop();
return true;
},
child: Scaffold(
appBar: AppBar(
// backgroundColor: Colors.white,
leading: InkWell(
onTap: () {
Navigator.of(context).pop();
},
child: Container(
child: Padding(
padding: EdgeInsets.only(top: 8.0, left: 12),
child: Stack(
children: [
Container(
// color: Colors.red,
width: 60.0,
height: 60.0,
// margin: EdgeInsets.all(8.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
fit: BoxFit.fill,
image: NetworkImage(widget.userphoto),
),
),
),
Padding(
padding: const EdgeInsets.only(left: 32.0),
child: Container(
// color: Colors.red,
width: 15.0,
height: 15.0,
// margin: EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.orange,
shape: BoxShape.circle,
),
),
),
],
),
),
),
),
title: Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () {
Navigator.of(context).pop();
},
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
widget.username,
style: TextStyle(
fontWeight: FontWeight.w400,
color: Colors.white,
fontSize: 20,
),
),
Text(
"Online",
style: TextStyle(
fontWeight: FontWeight.w400,
color: Colors.white,
fontSize: 15,
),
),
],
),
),
),
),
actions: <Widget>[
IconButton(
icon: SvgPicture.asset(
'assets/icons/notification/options.svg',
color: Colors.white,
),
onPressed: () {
print('Click start');
},
),
],
),
body: SafeArea(
child: Stack(
fit: StackFit.loose,
children: [
Column(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
// Text("data"),
// SizedBox(
// height: 50,
// ),
Flexible(
fit: FlexFit.tight,
child: Container(
width: MediaQuery.of(context).size.width,
// height: SizeConfig.safeBlockVertical * 80,
child: SingleChildScrollView(
controller: _scrollController,
child: ListView.builder(
shrinkWrap: true,
// reverse: true,
physics: ClampingScrollPhysics(),
scrollDirection: Axis.vertical,
itemCount: _msgLists.length,
itemBuilder: (context, index) {
return Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
SizedBox(
height: 10,
),
_msgLists[index].senderId == _id
? Row(
children: [
Expanded(
child: Container(),
),
Expanded(
child: Container(
child: Row(
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisAlignment:
MainAxisAlignment.end,
children: [
Flexible(
child: Container(
// width: 300.0,
// height: 300.0,
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
),
borderRadius:
BorderRadius
.circular(16.0),
),
child: Padding(
padding:
const EdgeInsets
.all(8.0),
child: Text(
_msgLists[index]
.msgText,
style: TextStyle(
color: Colors.black,
),
),
),
),
),
Padding(
padding:
const EdgeInsets.all(
8.0),
child: Column(
children: [
Container(
// color: Colors.red,
width: 60.0,
height: 60.0,
// margin: EdgeInsets.all(8.0),
decoration:
BoxDecoration(
shape:
BoxShape.circle,
image:
DecorationImage(
fit: BoxFit.fill,
image: NetworkImage(
widget
.userphoto),
),
),
),
Text(DateFormat.Hm()
.format(_msgLists[
index]
.chatDateTime)),
],
),
),
],
),
),
),
],
)
: Row(
children: [
Expanded(
child: Container(
child: Row(
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisAlignment:
MainAxisAlignment.start,
children: [
Padding(
padding:
const EdgeInsets.all(
8.0),
child: Column(
children: [
Container(
// color: Colors.red,
width: 60.0,
height: 60.0,
// margin: EdgeInsets.all(8.0),
decoration:
BoxDecoration(
shape:
BoxShape.circle,
image:
DecorationImage(
fit: BoxFit.fill,
image: NetworkImage(
widget
.userphoto),
),
),
),
Text(DateFormat.Hm()
.format(_msgLists[
index]
.chatDateTime)),
],
),
),
Flexible(
child: Container(
// width: 300.0,
// height: 300.0,
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
),
borderRadius:
BorderRadius
.circular(16.0),
),
child: Padding(
padding:
const EdgeInsets
.all(8.0),
child: Text(
_msgLists[index]
.msgText,
style: TextStyle(
color: Colors.black,
),
),
),
),
),
],
),
),
),
Expanded(
child: Container(),
),
],
),
],
);
},
),
),
),
),
Container(
height: 50,
child: Row(
children: [
Expanded(
flex: 6,
child: Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Container(
height: 50,
child: Form(
// key: _formkey,
child: TextFormField(
textInputAction: TextInputAction.newline,
// focusNode: _msgFocus,
keyboardType: TextInputType.multiline,
controller: _msg,
style: TextStyle(
fontSize: 20,
color: Colors.blue[900],
letterSpacing: 1,
),
autofocus: false,
decoration: InputDecoration(
// border: InputBorder.none,
prefixIcon: Padding(
padding: const EdgeInsets.fromLTRB(
8.0, 10.0, 8.0, 8.0),
child: SvgPicture.asset(
'assets/icons/personalchat/emoji.svg',
color: Colors.blueGrey[700],
height: 20,
width: 20,
),
),
suffixIcon: InkWell(
onTap: () async {
final image = await picker.getImage(
source: ImageSource.gallery);
setState(() {
_image = File(image.path);
});
},
child: Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(
8.0, 10.0, 8.0, 8.0),
child: SvgPicture.asset(
'assets/icons/personalchat/link.svg',
height: 20,
width: 20,
),
),
),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(8.0),
),
borderSide: BorderSide(
color: Colors.grey[400],
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(8.0),
),
borderSide: BorderSide(
color: Colors.indigo[500],
),
),
// errorBorder: OutlineInputBorder(
// borderRadius: BorderRadius.all(
// Radius.circular(5.0),
// ),
// borderSide: BorderSide(
// color: Colors.red[900],
// ),
// ),
// focusedErrorBorder: OutlineInputBorder(
// borderRadius: BorderRadius.all(
// Radius.circular(5.0),
// ),
// borderSide: BorderSide(
// color: Colors.red[900],
// ),
// ),
contentPadding:
EdgeInsets.fromLTRB(12, 8, 12, 8),
hintText: "Type a Message",
hintStyle: TextStyle(
fontSize: 15,
// color: Colors.grey[200],
),
),
),
),
),
),
),
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.only(left: 8.0),
child: InkWell(
onTap: () async {
// print("send");
if (_msg.text != '') {
final Msgsend response = await msgSend(
_id, widget.userid, "0", _msg.text, "");
if (response.server[0].result == 'success') {
print('msg send');
// setState(() {
// Navigator.of(context)
// .pushAndRemoveUntil(
// MaterialPageRoute(
// builder: (context) =>
// PersonalChat1(
// widget.userid,
// widget.username,
// widget.userphoto,
// ),
// ),
// (Route<dynamic> route) =>
// false);
// });
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => PersonalChat1(
widget.userid,
widget.username,
widget.userphoto),
),
);
} else {
print('error');
}
} else {
Fluttertoast.showToast(
msg: "Message is Empty",
backgroundColor: Colors.red,
textColor: Colors.white);
}
},
child: Container(
child: SvgPicture.asset(
'assets/icons/personalchat/send.svg',
),
),
),
),
),
],
),
),
],
),
],
),
),
bottomNavigationBar: BottomBar(),
),
);
}
}

How I call _email in a container ? in Flutter Android pp

I need to display JWT token values in a Container . I trying many ways return the value ,declare a global variable but doesn't work . when I declare a global variable it send NULL value. How Can I do that ?
I developed my app using Flutter
my code
class _ProfileScreenState extends State<ProfileScreen> {
SharedPreferences sharedPreferences;
String _email;
final _scaffoldKey = new GlobalKey<ScaffoldState>();
#override
void initState() {
super.initState();
checkLoginStatus();
}
checkLoginStatus() async {
sharedPreferences = await SharedPreferences.getInstance();
if(sharedPreferences.getString("token") == null) {
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) => Login()), (Route<dynamic> route) => false);
}
var token = sharedPreferences.getString("token");
var payload = Jwt.parseJwt(token);
print(payload);
print(payload["email"]);
_email = payload["email"];
print("Hello world");
print(_email);
return _email;
}
I want to send that email value to container.
My container section is here
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.redAccent[200],
child: Icon(Icons.arrow_back),
onPressed: () {
sharedPreferences.clear();
sharedPreferences.commit();
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) => Login()), (Route<dynamic> route) => false);
},
),
backgroundColor: Color.fromRGBO(255, 255, 255, .9),
body: SafeArea(
child: ListView(
children: <Widget>[
Stack(
children: <Widget>[
Container(
width: double.infinity,
height: 330,
color: Colors.blueAccent[200],
),
Positioned(
top: 10,
right: 30,
child: Icon(
Icons.settings, //setting Icon
color: Colors.white,
),
),
Column(
children: <Widget>[
Container(
height: 90,
margin: EdgeInsets.only(top: 60),
child: CircleAvatar(
radius: 50,
backgroundColor: Colors.white,
child: Icon(Icons.tag_faces),
)
),
Padding(
padding: EdgeInsets.all(4),
),
Text(
_email, // here I call that variable
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
fontSize: 20,fontFamily: 'Montserrat'),
textAlign: TextAlign.center,
),
add null check
Text(
_email == null || _email.isEmpty ?'Loading (or) nil' : _email,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
fontSize: 20,fontFamily: 'Montserrat'),
textAlign: TextAlign.center),