i want to edit a listview item when i click on it. I managed (with inkwell) that when I click on a listview item, the bottomsheet opens again where I also create new listview items, but I just can't edit it. I've tried everything I know (I don't know much I'm a beginner). here my codes.
--main.dart--
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import '/model/transaction.dart';
import '/widget/chart.dart';
import '/widget/new_transaction.dart';
import '/widget/transactoin_list.dart';
void main() {
// WidgetsFlutterBinding.ensureInitialized();
// SystemChrome.setPreferredOrientations(
// [
// DeviceOrientation.portraitUp,
// DeviceOrientation.portraitDown,
// ],
// );
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [
Locale("de"),
Locale("en"),
],
debugShowCheckedModeBanner: false,
title: "URLI",
theme: ThemeData(
primarySwatch: Colors.lightGreen,
fontFamily: "JosefinSans",
textTheme: ThemeData()
.textTheme
.copyWith(
headline4: const TextStyle(
fontFamily: "Tochter",
fontSize: 21,
),
headline5: const TextStyle(
fontFamily: "Bombing",
fontSize: 27,
letterSpacing: 3,
),
headline6: const TextStyle(
fontSize: 21,
fontWeight: FontWeight.w900,
),
)
.apply(
bodyColor: Colors.orangeAccent,
displayColor: Colors.orangeAccent.withOpacity(0.5),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
onPrimary: Colors.white,
primary: Theme.of(context).appBarTheme.backgroundColor,
textStyle: const TextStyle(
fontWeight: FontWeight.bold,
),
),
),
appBarTheme: const AppBarTheme(
titleTextStyle: TextStyle(
fontSize: 60,
fontFamily: "Tochter",
),
),
),
home: const AusgabenRechner(),
);
}
}
class AusgabenRechner extends StatefulWidget {
const AusgabenRechner({Key? key}) : super(key: key);
#override
State<AusgabenRechner> createState() => _AusgabenRechnerState();
}
class _AusgabenRechnerState extends State<AusgabenRechner> {
void _submitAddNewTransaction(BuildContext ctx) {
showModalBottomSheet(
context: ctx,
builder: (_) {
return GestureDetector(
onTap: () {},
child: NewTransaction(addNewTx: _addNewTransaction),
behavior: HitTestBehavior.opaque,
);
},
);
}
bool _showChart = false;
final List<Transaction> _userTransactions = [
// Transaction(
// id: "tx1",
// tittel: "Schuhe",
// preis: 99.99,
// datum: DateTime.now(),
// ),
// Transaction(
// id: "tx2",
// tittel: "Jacke",
// preis: 39.99,
// datum: DateTime.now(),
// ),
];
List<Transaction> get _recentTransactions {
return _userTransactions
.where(
(tx) => tx.datum.isAfter(
DateTime.now().subtract(
const Duration(days: 7),
),
),
)
.toList();
}
void _addNewTransaction(
String txTittel,
double txPreis,
DateTime choosenDate,
) {
final newTx = Transaction(
id: DateTime.now().toString(),
tittel: txTittel,
preis: txPreis,
datum: choosenDate,
);
setState(() {
_userTransactions.add(newTx);
});
}
void _deletedTransaction(String id) {
setState(() {
_userTransactions.removeWhere((tdddx) => tdddx.id == id);
});
}
#override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
final isInLandscape = mediaQuery.orientation == Orientation.landscape;
final appBar = AppBar(
centerTitle: true,
toolbarHeight: 99,
actions: [
IconButton(
onPressed: () => _submitAddNewTransaction(context),
icon: const Icon(
Icons.add,
color: Colors.white,
),
),
],
title: const Text(
"Ausgaben",
),
);
final txListWidget = SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.45,
child: TransactionList(
transaction: _userTransactions,
delettx: _deletedTransaction,
showNewTransaction: _submitAddNewTransaction,
),
);
return Scaffold(
appBar: appBar,
body: SingleChildScrollView(
child: Column(
children: [
if (isInLandscape)
SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.2,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Chart anzeigen",
style: Theme.of(context).textTheme.headline5,
),
const SizedBox(width: 9),
Switch.adaptive(
inactiveTrackColor:
Theme.of(context).primaryColor.withOpacity(0.3),
activeColor: Theme.of(context).primaryColor,
value: _showChart,
onChanged: (val) {
setState(() {
_showChart = val;
});
},
),
],
),
),
if (!isInLandscape)
SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.24,
child: Chart(
recentTransactions: _recentTransactions,
),
),
if (!isInLandscape)
SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.65,
child: txListWidget),
if (isInLandscape)
_showChart
? SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.51,
child: Chart(
recentTransactions: _recentTransactions,
),
)
: SizedBox(
height: (mediaQuery.size.height -
appBar.preferredSize.height -
mediaQuery.padding.top) *
0.81,
child: txListWidget)
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
child: const Icon(
Icons.add,
color: Colors.white,
),
onPressed: () => _submitAddNewTransaction(context),
),
);
}
}
--transaction_list.dart--
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '/model/transaction.dart';
class TransactionList extends StatefulWidget {
const TransactionList({
Key? key,
required this.transaction,
required this.delettx,
required this.showNewTransaction,
}) : super(key: key);
final List<Transaction> transaction;
final Function delettx;
final Function showNewTransaction;
#override
State<TransactionList> createState() => _TransactionListState();
}
class _TransactionListState extends State<TransactionList> {
#override
Widget build(BuildContext context) {
return widget.transaction.isEmpty
? LayoutBuilder(
builder: (ctx, contrains) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"Keine Daten vorhanden!",
style: Theme.of(context).textTheme.headline6,
),
const SizedBox(
height: 30,
),
SizedBox(
height: contrains.maxHeight * 0.45,
child: Image.asset(
"assets/images/schlafen.png",
fit: BoxFit.cover,
),
)
],
);
},
)
: Align(
alignment: Alignment.topCenter,
child: ListView.builder(
shrinkWrap: true,
reverse: true,
itemCount: widget.transaction.length,
itemBuilder: (ctx, index) {
return InkWell(
onLongPress: () => widget.showNewTransaction(ctx),
child: Card(
elevation: 5,
child: ListTile(
leading: CircleAvatar(
radius: 33,
child: Padding(
padding: const EdgeInsets.all(9.0),
child: FittedBox(
child: Row(
children: [
Text(
widget.transaction[index].preis
.toStringAsFixed(2),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 24,
),
),
const Text(
"€",
style: TextStyle(
fontSize: 21,
),
)
],
),
),
),
),
title: Text(
widget.transaction[index].tittel,
style: Theme.of(context).textTheme.headline6,
),
subtitle: Text(
DateFormat.yMMMMd("de")
.format(widget.transaction[index].datum),
style: Theme.of(context).textTheme.headline4,
),
trailing: MediaQuery.of(context).size.width > 460
? TextButton.icon(
onPressed: () =>
widget.delettx(widget.transaction[index].id),
icon: const Icon(
Icons.delete_outline,
),
label: const Text("Löschen"),
style: TextButton.styleFrom(
primary: Colors.red,
),
)
: IconButton(
onPressed: () =>
widget.delettx(widget.transaction[index].id),
icon: const Icon(
Icons.delete_outline,
color: Colors.red,
),
),
),
),
);
},
),
);
}
}
--new_transaction.dart--
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class NewTransaction extends StatefulWidget {
const NewTransaction({Key? key, required this.addNewTx}) : super(key: key);
final Function addNewTx;
#override
State<NewTransaction> createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _tittelcontroller = TextEditingController();
final _preiscontroller = TextEditingController();
DateTime? _selectedDate;
void _submitData() {
final enteredTittel = _tittelcontroller.text;
final enteredPreis = double.parse(_preiscontroller.text);
if (_preiscontroller.text.isEmpty) {
return;
}
if (enteredTittel.isEmpty || enteredPreis <= 0 || _selectedDate == null) {
return;
}
widget.addNewTx(
_tittelcontroller.text,
double.parse(_preiscontroller.text),
_selectedDate,
);
Navigator.of(context).pop();
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2022),
lastDate: DateTime.now(),
).then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_selectedDate = pickedDate;
});
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
bottom: false,
child: SingleChildScrollView(
child: Container(
//height: MediaQuery.of(context).size.height * 0.5,
padding: EdgeInsets.only(
top: 10,
left: 18,
right: 18,
bottom: MediaQuery.of(context).viewInsets.bottom + 10,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
TextButton(
onPressed: _submitData,
child: Text(
"hinzufügen",
style: Theme.of(context).textTheme.headlineSmall,
),
),
TextField(
controller: _tittelcontroller,
onSubmitted: (_) => _submitData(),
decoration: const InputDecoration(
label: Text("Tittel"),
),
),
TextField(
controller: _preiscontroller,
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
onSubmitted: (_) => _submitData(),
decoration: const InputDecoration(
label: Text("Preis"),
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 66),
child: Center(
child: Column(
children: [
Text(
_selectedDate == null
? "Kein Datum ausgewählt"
: DateFormat.yMMMMEEEEd("de")
.format(_selectedDate!),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
const SizedBox(
height: 21,
),
ElevatedButton(
style: Theme.of(context).elevatedButtonTheme.style,
onPressed: _presentDatePicker,
child: const Text("Datum wählen"),
),
],
),
),
)
],
),
),
),
);
}
}
EN: Here is an excample code, how i would solve this, when i understood the problem. The passing of the variables to the new Class is a bit differnent then in your Code but it works the same.
DE: So hier ist jetzt ein Beispielcode, wie ich es lösen würde, wenn ich das Problem richtig verstanden habe, dabei werden die Variabeln etwas anders als bei dir in die neue Klasse übergeben, funktioniert aber gleich
class testListview extends StatefulWidget {
var transaction;
var delettx;
var showNewTransaction;
//Passing the data to new Class
testListview(this.transaction, this.delettx,
this.showNewTransaction);
#override
State<testListview> createState() => _testListviewState();
}
class _testListviewState extends State<testListview> {
var transaction;
var delettx;
var showNewTransaction;
//Pass the data into the State of the new Class
_testListviewState(this.transaction, this.delettx,
this.showNewTransaction);
var transaction_2;
//The init state will be called in the first initialization of
//the Class
#override
void initState() {
//Pass your transactions to a new variable
setState(() {
transaction_2 = transaction;
});
super.initState();
}
#override
Widget build(BuildContext context) {
return ListView.builder(itemBuilder: (BuildContext context,
index){
return TextButton(onPressed: (){
//Change the data with onPressed
setState(() {
transaction_2["preis"] = "500";
});
}, child: Text(transaction_2["preis"]));
});}}
Related
i'm pretty new to programming and currently facing an issue where one of my screens wont display. The screen is sort of like a shopping cart screen where it displays the items the user has chosen. I'm very lost because for some reason flutter tells me the error is located in MaterialApp in main.
Here is my main.dart
import 'package:eat_easy_project/assistantMethod/shopping_List_Counter.dart';
import 'package:eat_easy_project/global/global.dart';
import 'package:eat_easy_project/splashScreen/splash_screen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:provider/provider.dart';
Future<void> main() async
{
WidgetsFlutterBinding.ensureInitialized();
sharedPreferences = await SharedPreferences.getInstance();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (c)=> ShoppingListCounter()),
],
child: MaterialApp(
title: 'EatEasy Project',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MySplashScreen(),
),
);
}
}
and below is the cart screen where it the other code where it shoul've displayed
import 'package:eat_easy_project/models/ingredients.dart';
import 'package:flutter/material.dart';
class ShoppingListDesign extends StatefulWidget
{
final Ingredients? model;
BuildContext? context;
final List <int>? separateIngredientQuantitiesList;
ShoppingListDesign({
this.model,
this.context,
this.separateIngredientQuantitiesList,
});
#override
State<ShoppingListDesign> createState() => _ShoppingListDesignState();
}
class _ShoppingListDesignState extends State<ShoppingListDesign> {
#override
Widget build(BuildContext context) {
return InkWell(
splashColor: Colors.cyan,
child: Padding(
padding: const EdgeInsets.all(6.0),
child: Container(
height: 165,
width: MediaQuery.of(context).size.width,
child: Row(
children: [
Image.network(widget.model!.ingredientAvatarUrl!, width: 140, height: 120,),
const SizedBox(width: 6,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.model!.ingredientName!,
style: const TextStyle(
color: Colors.black,
fontSize: 16,
fontFamily: "Kiwi",
),
),
const SizedBox(
height: 1.0,
),
Row(
children: [
const Text(
"x ",
style: TextStyle(
color: Colors.black,
fontSize: 25,
fontFamily: "Acme",
),
),
Text(
widget.separateIngredientQuantitiesList.toString(),
style: const TextStyle(
color: Colors.black,
fontSize: 25,
fontFamily: "Acme",
),
),
],
),
Row(
children: [
const Text(
"Price: ",
style: TextStyle(
fontSize: 15,
color: Colors.grey,
),
),
const Text(
"RM ",
style: TextStyle(
fontSize: 15,
color: Colors.grey,
),
),
Text(
widget.model!.ingredientPrice.toString(),
style: const TextStyle(
fontSize: 15,
color: Colors.grey,
),
),
],
)
],
),
],
),
),
),
);
}
}
I'm following a guide from udemy to help me code and for some reason even though I copied the exact same code with minor adjustments, I still got this error. My database json is located in firebase.
Error in detail:
enter image description here
Error for assitantMethod led me to var quanNumber = int.parse(listIngredientCharacters1.toString());
separateIngredientUIDs()
{
List<String> separateIngredientUIDsList=[], defaultIngredientList=
[];
int i=0;
defaultIngredientList =
sharedPreferences!.getStringList("userShoppingList")!;
for(i; i<defaultIngredientList.length; i++)
{
String ingredient = defaultIngredientList[i].toString();
var pos = ingredient.lastIndexOf(":");
String getIngredientID = (pos != -1) ? ingredient.substring(0, pos)
: ingredient;
print("\nThis is ingredientID now = " + getIngredientID);
separateIngredientUIDsList.add(getIngredientID);
}
print("\nThis is Ingredients List now = " );
print(separateIngredientUIDsList);
return separateIngredientUIDsList;
}
addIngredientToCart(String? ingredientUID, BuildContext context, int
ingredientCounter)
{
List<String>? tempList =
sharedPreferences!.getStringList("userShoppingList");
tempList!.add(ingredientUID! + ":$ingredientCounter");
FirebaseFirestore.instance.collection("user")
.doc(firebaseAuth.currentUser!.uid).update({
"userShoppingList": tempList,
}).then((value)
{
Fluttertoast.showToast(msg: "Ingredient Added Successfully.");
sharedPreferences!.setStringList("userShoppingList", tempList);
//update badge
Provider.of<ShoppingListCounter>(context, listen:
false).displayShoppingListIngredientNumber();
});
}
separateIngredientQuantities()
{
List<int> separateIngredientQuantityList=[];
List<String> defaultIngredientList=[];
int i=0;
defaultIngredientList =
sharedPreferences!.getStringList("userShoppingList")!;
for(i; i<defaultIngredientList.length; i++)
{
String ingredient = defaultIngredientList[i].toString();
List<String> listIngredientCharacters =
ingredient.split(":").toList();
var quanNumber = int.parse(listIngredientCharacters[0].toString());
print("\nThis is Quantity Number = " + quanNumber.toString());
separateIngredientQuantityList.add(quanNumber);
}
print("\nThis is Quantity List now = " );
print(separateIngredientQuantityList);
return separateIngredientQuantityList;
}
Error for shoppinglistscreen led me to separateIngredientQuantities();
class ShoppingListScreen extends StatefulWidget {
Ingredients? model;
ShoppingListScreen({this.model});
#override
State<ShoppingListScreen> createState() => _ShoppingListScreenState();
}
class _ShoppingListScreenState extends State<ShoppingListScreen>
{
#override
void initState() {
super.initState();
separateIngredientQuantities();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar
(
flexibleSpace: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Color.fromARGB(255, 192, 234, 240),
Color.fromARGB(255, 108, 173, 70),
],
begin: FractionalOffset(0.0, 0.0),
end: FractionalOffset(1.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp,
)
),
),
title: const Text(
"EatEasy",
style: TextStyle(color: Colors.white, fontWeight:
FontWeight.bold,)
),
centerTitle: true,
automaticallyImplyLeading: true,
actions: [
Stack(
children: [
IconButton(
icon: const Icon(Icons.shopping_cart, color: Colors.cyan,),
onPressed: ()
{
Navigator.push(context, MaterialPageRoute(builder: (c)=>
ShoppingListScreen(model: widget.model,)));
},
),
Positioned(
child: Stack(
children: [
const Icon(
Icons.brightness_1,
size: 20.0,
color: Color.fromARGB(255, 29, 88, 31),
),
Positioned(
top: 3,
right: 4,
child: Center(
child: Consumer<ShoppingListCounter>(
builder: (context, counter, c)
{
return Text(
counter.count.toString(),
style: const TextStyle(color: Color.fromARGB(255, 209, 218, 226)),
);
}
),
),
),
],
),
),
],
),
],
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SizedBox(width: 10,),
Align(
alignment: Alignment.bottomLeft,
child: FloatingActionButton.extended(
label: const Text("Clear List", style: TextStyle(fontSize: 16),),
backgroundColor: Colors.cyan,
icon: const Icon(Icons.clear_all),
onPressed: ()
{
},
),
),
Align(
alignment: Alignment.bottomLeft,
child: FloatingActionButton.extended(
label: const Text("Calculate Total", style: TextStyle(fontSize: 16),),
backgroundColor: Colors.cyan,
icon: const Icon(Icons.calculate),
onPressed: ()
{
},
),
)
],
),
body: CustomScrollView(
slivers: [
//overall total amount
SliverPersistentHeader(
pinned: true,
delegate: TextWidgetHeader(title: "Total Amount = 120"),
),
//display cart ingredients with quantity
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("ingredients")
.where("ingredientUID", whereIn: separateIngredientUIDs())
.orderBy("ingredientPrice", descending: true)
.snapshots(),
builder: (context, snapshot)
{
return !snapshot.hasData
? SliverToBoxAdapter(child: Center(child:
circularProgress()),)
: snapshot.data!.docs.length == 0
? //startBuildingList
Container()
: SliverList(
delegate: SliverChildBuilderDelegate((context, index)
{
Ingredients model = Ingredients.fromJson(
snapshot.data!.docs[index].data()! as Map<String,
dynamic>,
);
return ShoppingListDesign(
model: model,
context: context,
separateIngredientQuantitiesList: [index] ,
);
},
//childCount: snapshot.hasData ?
snapshot.data!.docs.length : 0,
),
);
},
),
],
),
);
}
}
am building a flutter app and am am working with a data from a API i got the list and evreything i did a search bar that works properly by typing either the number of the ticket or the description but am trying to add a new filter , a checkbox that filters the data i have 2 problems
1: when i press on a checkbox and type confirm it works and it shows but the checkbox dosent stay checked
2: how can i implement it so it filter the data from the api directly
and thank you
// ignore_for_file: use_key_in_widget_constructors, avoid_print, avoid_unnecessary_containers, curly_braces_in_flow_control_structures, prefer_const_constructors, non_constant_identifier_names, unnecessary_new, avoid_function_literals_in_foreach_calls, unused_import, avoid_types_as_parameter_names, unused_label, unused_element, file_names, library_private_types_in_public_api, unnecessary_string_interpolations
import 'dart:convert';
import 'dart:io';
import 'package:az/Actifs.dart';
import 'package:az/SR_Details.dart';
import 'package:az/main.dart';
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'class/sr.dart';
import 'package:dropdown_search/dropdown_search.dart';
class DataFromAPI extends StatefulWidget {
#override
_DataFromAPIState createState() => _DataFromAPIState();
}
List<Sr> _MyAllData=[];
List<Sr> _SrForDsiplay=[];
Map<String, Color> map={
"QUEUED":Color.fromARGB(255, 255, 136, 0),
"CLOSED":Colors.grey,
"Rejected":Colors.red,
"INPROG":Colors.green,
"PENDING":Colors.blue,
"RESOLVED":Colors.green,
"NEW":Colors.blue,
};
Map<String, String> map1={
"1":"Urgent",
"2":"High",
"3":"Medium",
"4":"Low",
};
/*Map<String, Color> map3={
"Urgent":Colors.red,
"High":Color.fromARGB(255, 255, 139, 131),
"Medium":Colors.blue,
"Low":Colors.green,
"null":Colors.grey,
};*/
class Multiselect extends StatefulWidget {
final List<String> items;
const Multiselect({Key? key, required this.items}) : super(key: key);
#override
State<Multiselect> createState() => _MultiselectState();
}
class _MultiselectState extends State<Multiselect> {
final List<String> _selectedItems=[];
void _itemChange(String itemValue, bool isSelected) {
setState(() {
if (isSelected) {
_selectedItems.add(itemValue);
} else {
_selectedItems.remove(itemValue);
}
});
}
// this function is called when the Cancel button is pressed
void _cancel() {
Navigator.pop(context);
}
// this function is called when the Submit button is tapped
void _submit() {
Navigator.pop(context, _selectedItems);
}
#override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Select Topics'),
content: SingleChildScrollView(
child: ListBody(
children: widget.items
.map((item) => CheckboxListTile(
value: _selectedItems.contains(item),
title: Text(item),
controlAffinity: ListTileControlAffinity.leading,
onChanged: (isChecked) => _itemChange(item, isChecked!),
))
.toList(),
),
),
actions: [
TextButton(
onPressed: _cancel,
child: const Text('Cancel'),
),
ElevatedButton(
onPressed: _submit,
child: const Text('Submit'),
),
],
);
}
}
class _DataFromAPIState extends State<DataFromAPI> {
List<String> _selectedItems=[];
String title_string = "Liste des SR :";
void _ShowMultiSelect() async{
final List<String> items=[
'QUEUED',
'CLOSED',
'Rejected',
'INPROG',
'PENDING',
'RESOLVED',
'NEW',
];
final List<String>? results =await showDialog(
context: context,
builder: (BuildContext context) {
return Multiselect(items: items);
},
);
if(results !=null){
setState(() {
_selectedItems=results;
});
}
}
#override
void initState() {
loadData().then((value) {
_MyAllData.clear();
setState(() {
_MyAllData.addAll(value);
_SrForDsiplay=_MyAllData;
});
});
super.initState();
}
Future<List<Sr>> loadData() async {
try {
var response = await http.get(Uri.parse(
'http:MXSR/?_lid=&_lpwd=&_format=json'));
if (response.statusCode == 200) {
final jsonBody = json.decode(response.body);
Demandes data = Demandes.fromJson(jsonBody);
final srAttributes = data.queryMxsrResponse.mxsrSet.sr;
title_string='Liste des SR : ${srAttributes.length.toString()}';
return srAttributes;
}
} catch (e) {
throw Exception(e.toString());
}
throw Exception("");
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner:false,
home: new Scaffold(resizeToAvoidBottomInset: false ,
appBar: AppBar(
title: Text(title_string),
leading: IconButton(
icon: Icon(Icons.arrow_back), onPressed: () { Navigator.push(
context, MaterialPageRoute(builder: (context) => Home())); },
),
flexibleSpace: InkWell(onTap: () {
},),
),
body: FutureBuilder<List<Sr>?>(
future: loadData(),
builder: (context, snapshot) {
if (_MyAllData.isEmpty) {
return SizedBox(
height: MediaQuery.of(context).size.height / 1.3,
child: Center(
child: CircularProgressIndicator(),
),
);
} else { return
ListView(
children: <Widget>[Padding(
padding: const EdgeInsets.all(8.0),
child: Column(children:<Widget>[ElevatedButton(onPressed: _ShowMultiSelect,
child: const Text('Filter')),
const Divider(
height: 30,
),
Wrap(
children: _selectedItems
.map((e) => Chip(
label: Text(e),
))
.toList(),
),
Row(children:<Widget>[ Expanded(
child: TextField(
decoration:
InputDecoration( hintText: "Enter id or description"),
onChanged: (text) {
text=text.toLowerCase();
setState(() {
_SrForDsiplay =_MyAllData.where((srAttributes) {
var srDescription = srAttributes.attributes.description!.content.toString().toLowerCase();
var srID= srAttributes.attributes.ticketid.content.toString();
return srDescription.contains(text) || srID.contains(text);
}).toList();
title_string='Liste des SR : ${_SrForDsiplay.length.toString()}';
print(title_string);
}
);
},
)),])
],
),),
new ListView.builder(scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: _SrForDsiplay.length,
itemBuilder: ((_, index) {
return
new ListTile(
title: new Card(
margin: new EdgeInsets.symmetric(
vertical: 2.0, horizontal: 8.0),
elevation: 10,
child: new ListTile(
title: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(padding: new EdgeInsets.all(2.0)),
Row(children :[
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color.fromARGB(255, 255, 255, 255),
),
color: map['${_SrForDsiplay[index].attributes.status.content}'],
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child:Text(' ${_SrForDsiplay[index].attributes.status.content} '),
),
Container(child: Text(' '),),
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color.fromARGB(255, 255, 255, 255),
),
color:Colors.grey,
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child:Text( map1['${_SrForDsiplay[index].attributes.reportedpriority?.content}'] ?? " null "),
),
],
),
SizedBox(
height: 8,
),
Row(children: <Widget>[
Expanded( child: Container(child: Text('${_SrForDsiplay[index].attributes.description?.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600)),),),),
Expanded(child: Container(child:Text( ' ${_SrForDsiplay[index].attributes.ticketid.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w400)),)))
],),
new Divider(
color: Color.fromARGB(255, 110, 109, 109),
),
Text(
'Reported : ${DateFormat.yMMMMEEEEd().format(DateTime.parse('${_SrForDsiplay[index].attributes.statusdate.content}' ))}' ,
style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400)),
),
new Text(
'Reported by : ${_SrForDsiplay[index].attributes.reportedby?.content}',style: GoogleFonts.openSans(
textStyle: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400)),
),
Row(children: [new Image(image: AssetImage('assets/courroi.png'), width: 20),
Text(
'${_SrForDsiplay[index].relatedMbos?.asset[0].attributes.descriptionasset?.content}'),], ),
Row(children: [new Image(image: AssetImage('assets/emp.png'), width: 20),
Text(
'${_SrForDsiplay[index].attributes.assetsiteid?.content}'),], ) ,
Divider(
color: Color.fromARGB(255, 110, 109, 109),
),
Row(children:[
Expanded(child: Badge(
position: BadgePosition.topEnd(top: -8, end: 20),
badgeColor: Colors.grey,
badgeContent: Text('1'),
child :IconButton(icon :Icon(Icons.file_present_rounded), padding: const EdgeInsets.all(0),
onPressed: () {
},
),
)
),
Expanded(child: IconButton (
icon: Icon(Icons.file_copy),
onPressed: () { },
),),
Expanded(child: IconButton(onPressed:() {
}, icon: Icon(Icons.delete)) )
],)
],
),
trailing: Icon(Icons.arrow_forward_ios_rounded),
),
),
onTap: () {
Navigator.push(
context,MaterialPageRoute(builder: (context) =>SrDetailsScreen(sr: _SrForDsiplay[index])),
);
}
);
}
),
)
]
);
}
},
),
),
);
}
}
#main.dart file
import 'package:flutter/material.dart';
import './widgets/new_transaction.dart';
import './widgets/transaction_list.dart';
import './widgets/chart.dart';
import './models/tranasction.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Personal Expenses',
theme: ThemeData(
primarySwatch: Colors.purple,
accentColor: Colors.amber,
// errorColor: Colors.red,
fontFamily: 'Quicksand',
textTheme: ThemeData.light().textTheme.copyWith(
titleMedium: TextStyle(
fontFamily: 'OpenSans',
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
appBarTheme: AppBarTheme(
textTheme: ThemeData.light().textTheme.copyWith(
titleMedium: TextStyle(
fontFamily: 'OpenSans',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
)),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
// String titleInput;
// String amountInput;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final List<Transaction> _userTransactions = [
// Transaction(
// id: 't1',
// title: 'New Shoes',
// amount: 69.99,
// date: DateTime.now(),
// ),
// Transaction(
// id: 't2',
// title: 'Weekly Groceries',
// amount: 16.53,
// date: DateTime.now(),
// ),
];
List<Transaction> get _recentTransactions {
return _userTransactions.where((tx) {
return tx.date.isAfter(
DateTime.now().subtract(
Duration(days: 7),
),
);
}).toList();
}
void _addNewTransaction(
String txTitle, double txAmount, DateTime chosenDate) {
final newTx = Transaction(
title: txTitle,
amount: txAmount,
date: chosenDate,
id: DateTime.now().toString(),
);
setState(() {
_userTransactions.add(newTx);
});
}
void _startAddNewTransaction(BuildContext ctx) {
showModalBottomSheet(
context: ctx,
builder: (_) {
return GestureDetector(
onTap: () {},
child: NewTransaction(_addNewTransaction),
behavior: HitTestBehavior.opaque,
);
},
);
}
void _deleteTransaction(String id) {
setState(() {
_userTransactions.removeWhere((tx) => tx.id == id);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Personal Expenses',
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () => _startAddNewTransaction(context),
),
],
),
body: SingleChildScrollView(
child: Column(
// mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Chart(_recentTransactions),
TransactionList(_userTransactions, _deleteTransaction),
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => _startAddNewTransaction(context),
),
);
}
}
#new_transaction.dart file
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:flutter/src/widgets/framework.dart';
class NewTransaction extends StatefulWidget {
final Function addTx;
NewTransaction(this.addTx);
#override
_NewTransactionState createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _titleController = TextEditingController();
final _amountController = TextEditingController();
late DateTime _selectedDate;
void initState() {
_selectedDate:
DateTime.now();
super.initState();
}
void _submitData() {
if (_amountController.text.isEmpty) {
return;
}
final enteredTitle = _titleController.text;
final enteredAmount = double.parse(_amountController.text);
if (enteredTitle.isEmpty || enteredAmount <= 0 || _selectedDate == null) {
return;
}
widget.addTx(
enteredTitle,
enteredAmount,
_selectedDate,
);
Navigator.of(context).pop();
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now(),
).then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_selectedDate = pickedDate;
});
});
print('...');
}
#override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Title'),
controller: _titleController,
onSubmitted: (_) => _submitData(),
// onChanged: (val) {
// titleInput = val;
// },
),
TextField(
decoration: InputDecoration(labelText: 'Amount'),
controller: _amountController,
keyboardType: TextInputType.number,
onSubmitted: (_) => _submitData(),
// onChanged: (val) => amountInput = val,
),
Container(
height: 70,
child: Row(
children: <Widget>[
Expanded(
child: Text(
_selectedDate == null
? 'No Date Chosen!'
: 'Picked Date: ${DateFormat.yMd().format(_selectedDate)}',
),
),
FlatButton(
textColor: Theme.of(context).primaryColor,
child: Text(
'Choose Date',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
onPressed: _presentDatePicker,
),
],
),
),
RaisedButton(
child: Text('Add Transaction'),
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).textTheme.button?.color,
onPressed: _submitData,
),
],
),
),
);
}
#override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties
.add(DiagnosticsProperty<DateTime>('_selectedDate', _selectedDate));
}
}
#transaction_list.dart file
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/tranasction.dart';
class TransactionList extends StatelessWidget {
final List<Transaction> transactions;
TransactionList(
this.transactions, void Function(String id) deleteTransaction);
#override
Widget build(BuildContext context) {
return Container(
height: 300,
child: transactions.isEmpty
? Column(
children: <Widget>[
Text(
'No transactions added yet!',
style: Theme.of(context).textTheme.titleMedium,
),
SizedBox(
height: 20,
),
Container(
height: 200,
child: Image.asset(
'assets/images/waiting.png',
fit: BoxFit.cover,
)),
],
)
: ListView.builder(
itemBuilder: (ctx, index) {
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(
vertical: 8,
horizontal: 5,
),
child: ListTile(
leading: CircleAvatar(
radius: 30,
child: Padding(
padding: EdgeInsets.all(6),
child: FittedBox(
child: Text('\$${transactions[index].amount}'),
),
),
),
title: Text(
transactions[index].title,
style: Theme.of(context).textTheme.titleMedium,
),
subtitle: Text(
DateFormat.yMMMd().format(transactions[index].date),
),
),
);
},
itemCount: transactions.length,
),
);
}
}
#chart.dart file
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/tranasction.dart';
class TransactionList extends StatelessWidget {
final List<Transaction> transactions;
TransactionList(
this.transactions, void Function(String id) deleteTransaction);
#override
Widget build(BuildContext context) {
return Container(
height: 300,
child: transactions.isEmpty
? Column(
children: <Widget>[
Text(
'No transactions added yet!',
style: Theme.of(context).textTheme.titleMedium,
),
SizedBox(
height: 20,
),
Container(
height: 200,
child: Image.asset(
'assets/images/waiting.png',
fit: BoxFit.cover,
)),
],
)
: ListView.builder(
itemBuilder: (ctx, index) {
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(
vertical: 8,
horizontal: 5,
),
child: ListTile(
leading: CircleAvatar(
radius: 30,
child: Padding(
padding: EdgeInsets.all(6),
child: FittedBox(
child: Text('\$${transactions[index].amount}'),
),
),
),
title: Text(
transactions[index].title,
style: Theme.of(context).textTheme.titleMedium,
),
subtitle: Text(
DateFormat.yMMMd().format(transactions[index].date),
),
),
);
},
itemCount: transactions.length,
),
);
}
}
#chartbar.dart file
import 'package:flutter/material.dart';
class ChartBar extends StatelessWidget {
final String label;
final double spendingAmount;
final double spendingPctOfTotal;
ChartBar(this.label, this.spendingAmount, this.spendingPctOfTotal);
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
height: 20,
child: FittedBox(
child: Text('\$${spendingAmount.toStringAsFixed(0)}'),
),
),
SizedBox(
height: 4,
),
Container(
height: 60,
width: 10,
child: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey, width: 1.0),
color: Color.fromRGBO(220, 220, 220, 1),
borderRadius: BorderRadius.circular(10),
),
),
FractionallySizedBox(
heightFactor: spendingPctOfTotal,
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(10),
),
),
),
],
),
),
SizedBox(
height: 4,
),
Text(label),
],
);
}
}
#transaction.dart file
**i am using the latest version of flutter
and using android studio as emulator,
and using vs code as code editor my code has no errors,
but i keep getting this error after many attempts
i tested using real android device too but nothing changed error message:'package:flutter/src/widgets/framework.dart':failed
assertion:line4864 pos 12:'child==_child':is not true.
see also https://flutter.dev/docs/testing/errors **
I encountered a problem in making my app multilingual.
On the other pages of my app, when the code
S.of(context).myText is called, the code works correctly and And the text corresponding to the language chosen by the audience is displayed, but on the one class of my app named Home, by calling this program code, regardless of the selected language, only the English text is displayed shows even if I choose Malaysia or Arabic.
Interestingly, when I build the project with Chrome, there is no problem, but when I download the apk from it, it does not work on the mobile.
the problem is with S.of(context).Home_drawer_mainMenu, in below code:
my Home class:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';
import 'package:untitled22/SignUp.dart';
import 'package:untitled22/TabBarViewHome.dart';
import 'package:untitled22/loginFile.dart';
import './Page_1.dart';
import './Page_2.dart';
import './Page_3.dart';
import './Page_4.dart';
import 'LanguageChangeProvider.dart';
import 'package:untitled22/generated/l10n.dart';
void main() {
runApp(const MaterialApp(
home: HomePage(),
debugShowCheckedModeBanner: false,
));
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int pageNumb = 0;
late TabController _controller;
String _currentLanguage = 'ar';
bool rtl = false;
#override
void initState() {
_loadCounter();
super.initState();
}
_loadCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_currentLanguage = (prefs.getString('currentLang') ?? '');
rtl = (prefs.getBool('isRtl') ?? false);
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
locale: new Locale(_currentLanguage),
localizationsDelegates: [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: S.delegate.supportedLocales,
home: BodyBody(),
debugShowCheckedModeBanner: false,
showSemanticsDebugger: false,
);
}
}
class BodyBody extends StatefulWidget {
const BodyBody({Key? key}) : super(key: key);
#override
State<BodyBody> createState() => _BodyBodyState();
}
class _BodyBodyState extends State<BodyBody> with SingleTickerProviderStateMixin {
int pageNumb = 0;
late TabController _controller;
String _currentLanguage = '';
bool rtl = false;
#override
void initState() {
_loadCounter();
super.initState();
_controller = TabController(vsync: this, length: 3, initialIndex: 1);
}
_loadCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_currentLanguage = (prefs.getString('currentLang') ?? 'ar');
rtl = (prefs.getBool('isRtl') ?? false);
});
}
#override
Widget build(BuildContext context) {
Size media = MediaQuery.of(context).size;
var height = AppBar().preferredSize.height;
TextEditingController textController = TextEditingController();
return DefaultTabController(
initialIndex: 1,
length: 3,
child: Scaffold(
appBar: AppBar(
titleSpacing: 0,
title: Text(
S.of(context).Home_drawer_mainMenu,
style: TextStyle(
color: Color(0xFF434343),
fontSize: rtl == true ? 16 : 14,
),
),
backgroundColor: const Color(0xff26c6da),
leading: Builder(
builder: (BuildContext context) {
return Container(
child: IconButton(
icon: const Icon(Icons.menu),
onPressed: () {
Scaffold.of(context).openDrawer();
},
color: const Color(0xFF434343),
),
);
},
),
actions: <Widget>[
IconButton(
onPressed: () {
print(height);
},
icon: Icon(Icons.search),
padding: rtl == false ? const EdgeInsets.only(right: 10) : const EdgeInsets.only(left: 10),
color: const Color(0xFF434343),
),
IconButton(
onPressed: () {},
icon: Icon(Icons.settings),
padding: rtl == false ? const EdgeInsets.only(right: 15) : const EdgeInsets.only(left: 15),
color: const Color(0xFF434343),
),
],
bottom: TabBar(
controller: _controller,
labelColor: Color(0xff434343),
unselectedLabelColor: Color(0xff434343),
indicatorColor: Color(0xff434343),
automaticIndicatorColorAdjustment: false,
tabs: <Widget>[
Tab(
icon: Icon(Icons.event_note_outlined),
),
Tab(
icon: Icon(Icons.home_rounded),
),
Tab(
icon: Icon(Icons.add_alert),
),
],
),
),
body: TabBarView(
controller: _controller,
children: [
TabBarHome(width: media.width, height: media.height),
TabBarHome(width: media.width, height: media.height),
TabBarHome(width: media.width, height: media.height),
],
),
drawer: Drawer(
child: ListView(
children: [
GestureDetector(
onTap: () {
print('hey');
},
child: InkWell(
onTap: () {},
child: Container(
color: Colors.grey.shade100,
height: media.height * 0.2,
child: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 0.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Container(
height: 70,
width: 90,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
fit: BoxFit.fitWidth,
image: AssetImage("images/aga.png"),
)),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
"Text",
style: TextStyle(
fontSize: 17,
color: Colors.black87,
fontWeight: FontWeight.w600,
),
),
Text(
"The best leader",
textAlign: TextAlign.justify,
style: TextStyle(
fontSize: 15,
color: Colors.black87,
),
),
],
),
],
),
Container(
child: rtl == true ? Icon(Icons.keyboard_arrow_right_rounded) : Icon(Icons.keyboard_arrow_left_rounded),
),
],
),
),
),
),
),
),
Padding(
padding: EdgeInsets.all(10),
child: Text(
S.of(context).Home_drawer_mainMenu,
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w600),
),
),
ListTile(
leading: Icon(Icons.home),
title: Text('data'),
),
ListTile(
leading: Icon(Icons.add_call),
title: Text('call with us'),
),
],
),
),
),
);
}
}
The issue is that progress icons and continue button are hidden in my stepper (cancel button is visible). So when i click on the place where "continue" button should exists (next to Cancel button) the "continue" event is happening and its correct.
The strange thing is that when i use the same code in a new test project, i can see both buttons and icons. Maybe its related to my sidebar but i am not sure.
import 'package:flutter/material.dart';
import 'package:taamin/bloc/navigation_bloc/navigation_bloc.dart';
class MyOrdersPage extends StatefulWidget with NavigationStates{
#override
_MyOrdersPageState createState() => _MyOrdersPageState();
}
class _MyOrdersPageState extends State<MyOrdersPage> {
List<Step> steps = [
Step(
title: const Text('New Account'),
isActive: true,
state: StepState.complete,
content: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Email Address'),
),
TextFormField(
decoration: InputDecoration(labelText: 'Password'),
),
],
),
),
Step(
title: const Text('Address'),
isActive: true,
state: StepState.editing,
content: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Home Address'),
),
TextFormField(
decoration: InputDecoration(labelText: 'Postcode'),
),
],
),
),
Step(
state: StepState.error,
title: const Text('Avatar'),
subtitle: const Text("Error!"),
content: Column(
children: <Widget>[
CircleAvatar(
backgroundColor: Colors.red,
)
],
),
),
];
StepperType stepperType = StepperType.vertical;
int currentStep = 0;
bool complete = false;
next() {
currentStep + 1 != steps.length
? goTo(currentStep + 1)
: setState(() => complete = true);
}
cancel() {
if (currentStep > 0) {
goTo(currentStep - 1);
}
}
goTo(int step) {
setState(() => currentStep = step);
}
switchStepType() {
setState(() => stepperType == StepperType.horizontal
? stepperType = StepperType.vertical
: stepperType = StepperType.horizontal);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('Assurance Véhicule'),
),
body: Column(children: <Widget>[
complete ? Expanded(
child: Center(
child: AlertDialog(
title: new Text("Profile Created"),
content: new Text(
"Tada!",
),
actions: <Widget>[
new FlatButton(
child: new Text("Close"),
onPressed: () {
setState(() => complete = false);
},
),
],
),
),
)
: Expanded(
child: Stepper(
steps: steps,
type: stepperType,
currentStep: currentStep,
onStepContinue: next,
onStepTapped: (step) => goTo(step),
onStepCancel: cancel,
),
),
]),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.list),
onPressed: switchStepType,
),
);
}
}
and here is the code of my sidebar menu:
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:rxdart/rxdart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:taamin/bloc/navigation_bloc/navigation_bloc.dart';
import 'package:taamin/sidebar/menu_item.dart';
class SideBar extends StatefulWidget {
#override
_SideBarState createState() => _SideBarState();
}
class _SideBarState extends State<SideBar>
with SingleTickerProviderStateMixin<SideBar> {
AnimationController _animationController;
StreamController<bool> isSidebarOpenedStreamController;
Stream<bool> isSidebarOpenedStream;
StreamSink<bool> isSidebarOpenedSink;
final _animationDuration = const Duration(milliseconds: 500);
#override
void initState() {
super.initState();
_animationController =
AnimationController(vsync: this, duration: _animationDuration);
isSidebarOpenedStreamController = PublishSubject<bool>();
isSidebarOpenedStream = isSidebarOpenedStreamController.stream;
isSidebarOpenedSink = isSidebarOpenedStreamController.sink;
}
#override
void dispose() {
_animationController.dispose();
isSidebarOpenedStreamController.close();
isSidebarOpenedSink.close();
super.dispose();
}
void onIconPressed() {
final animationStatus = _animationController.status;
final isAnimationCompleted = animationStatus == AnimationStatus.completed;
//completed means sidebar is open
if (isAnimationCompleted) {
isSidebarOpenedSink.add(false);
_animationController.reverse();
} else {
isSidebarOpenedSink.add(true);
_animationController.forward();
}
}
#override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
return StreamBuilder<bool>(
initialData: false,
stream: isSidebarOpenedStream,
builder: (context, isSideBarOpenedAsync) {
return AnimatedPositioned(
duration: _animationDuration,
top: 0,
bottom: 0,
left: isSideBarOpenedAsync.data ? 0 : -screenWidth,
right: isSideBarOpenedAsync.data ? 0 : screenWidth - 30,
child: Row(
children: <Widget>[
Expanded(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 20),
color: const Color(0xFF262AAA),
child: Column(
children: <Widget>[
SizedBox(
height: 100,
),
ListTile(
title: Text(
"Yassine",
style: TextStyle(
color: Colors.white,
fontSize: 30,
fontWeight: FontWeight.w800),
),
subtitle: Text(
"firstname.name#gmail.com",
style: TextStyle(
color: Color(0xFF1BB5FD),
fontSize: 15,
),
),
leading: CircleAvatar(
child: Icon(
Icons.perm_identity,
color: Colors.white,
),
radius: 40,
),
),
Divider(
height: 64,
thickness: 0.5,
color: Colors.white.withOpacity(0.3),
indent: 32,
endIndent: 32,
),
MenuItem(
icon: Icons.home,
title: "Home",
onTap: () {
onIconPressed();
BlocProvider.of<NavigationBloc>(context).add(NavigationEvents.HomePageClickedEvent);
},
),
MenuItem(
icon: Icons.person,
title: "My Accounts",
onTap: () {
onIconPressed();
BlocProvider.of<NavigationBloc>(context).add(NavigationEvents.MyAccountClickedEvent);
},
),
MenuItem(
icon: Icons.directions_car,
title: "Assurance Véhicule",
onTap: () {
onIconPressed();
BlocProvider.of<NavigationBloc>(context).add(NavigationEvents.MyOrdersClickedEvent);
},
),
MenuItem(
icon: Icons.card_giftcard,
title: "Wishlist",
),
Divider(
height: 64,
thickness: 0.5,
color: Colors.white.withOpacity(0.3),
indent: 32,
endIndent: 32,
),
MenuItem(
icon: Icons.settings,
title: "Settings",
),
MenuItem(
icon: Icons.exit_to_app,
title: "Logout",
onTap: () {
onIconPressed();
exit(0);
}
),
],
),
),
),
Align(
alignment: Alignment(0, -0.9),
child: GestureDetector(
onTap: () {
onIconPressed();
},
child: ClipPath(
clipper: CustomMenuClipper(),
child: Container(
width: 35,
height: 110,
color: Color(0xFF262AAA),
alignment: Alignment.centerLeft,
child: AnimatedIcon(
progress: _animationController.view,
icon: AnimatedIcons.menu_close,
color: Color(0xFF1BB5FD),
size: 25,
),
),
),
),
)
],
),
);
},
);
}
}
class CustomMenuClipper extends CustomClipper<Path> {
#override
Path getClip(Size size) {
Paint paint = Paint();
paint.color = Colors.white;
final width = size.width;
final height = size.height;
Path path = Path();
path.moveTo(0, 0);
path.quadraticBezierTo(0, 8, 10, 16);
path.quadraticBezierTo(width - 1, height / 2 - 20, width, height / 2);
path.quadraticBezierTo(width + 1, height / 2 + 20, 10, height - 16);
path.quadraticBezierTo(0, height - 8, 0, height);
path.close();
return path;
}
#override
bool shouldReclip(CustomClipper<Path> oldClipper) {
return false;
}
}
add controlsBuilder inside stepper
controlsBuilder: (BuildContext context,
{VoidCallback onStepContinue, VoidCallback onStepCancel}) {
return Row(
children: <Widget>[
FlatButton(
onPressed: onStepContinue,
child: const Text('Continue',
style: TextStyle(color: Colors.white)),
color: Colors.redAccent,
),
new Padding(
padding: new EdgeInsets.all(10),
),
FlatButton(
onPressed: onStepCancel,
child: const Text(
'Cancel',
style: TextStyle(color: Colors.white),
),
color: Colors.black,
),
],
);
},