Wednesday, February 3, 2021

Sử dụng nút lệnh FlatButton và hiện thông báo bằng SnackBar trong Flutter

Bài này thực hành việc khi bấm vào nút lệnh thì sẽ hiện lên thông tin của các giá trị trong TextField và hiển thị dưới dạng thông báo 2 giây trên SnackBar.

snackBar trong flutter

Code:

import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return _MyAppState();
}
}

class _MyAppState extends State<MyApp> {
final GlobalKey<ScaffoldState> _scaffoldkey = GlobalKey<ScaffoldState>();
final _costeditingcontroler = new TextEditingController();
final _amounteditingcontroler = new TextEditingController();
String _cost = '';
double _amount = 0.0 ;

@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(

title:
"Test",
home: Scaffold(
key: _scaffoldkey,
appBar: AppBar(
title:
Text("Cost Managerment")),
body: SafeArea(
minimum:
EdgeInsets.all(10),
child: Container(
padding:
EdgeInsets.symmetric(horizontal: 10),
child: Column(
mainAxisAlignment: MainAxisAlignment.
start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(padding: EdgeInsets.symmetric(vertical: 10),
child: Text("Enter your income today?",
style: TextStyle(
fontSize:
20,fontWeight: FontWeight.bold),
textAlign: TextAlign.left,),),
TextField(
controller:
_costeditingcontroler,
decoration: InputDecoration(
border:
OutlineInputBorder(
borderRadius:
BorderRadius.circular(10),),
labelText: "What is your cost?",
icon: Icon(Icons.local_cafe_outlined)


)
,
),
Padding(padding: EdgeInsets.symmetric(vertical: 10),
child: TextField(
controller:
_amounteditingcontroler,
decoration: InputDecoration(
border:
OutlineInputBorder(
borderRadius:
BorderRadius.circular(10),),
labelText: "Amount of money?",
icon: Icon(Icons.money)

)
,
)),
Column(crossAxisAlignment: CrossAxisAlignment.end,children: [
FlatButton(onPressed: (
){
setState(() {
_cost=_costeditingcontroler.text;
_amount= double.tryParse(_amounteditingcontroler.text) ?? 0;
_scaffoldkey.currentState.showSnackBar(
SnackBar(
content: Text("Cost: $_cost - Amount: " + (NumberFormat('###,###.0#','en_US').format(_amount)).toString()),
duration: Duration(seconds: 2)
,

));
});
},
child: Text("Add Cost"),
color: Colors.green,
textColor: Colors.white,)
]
,),

],),
),)

)
,
);
}
}

Nếu thấy hữu ích hảy chia sẻ bài viết này trên:  

0 nhận xét:

Post a Comment