How can I search the button I made in ListView with Search Bar? - flutter

I created a button shape called 'VocabularyWordsButton' and when I try it under a ListView it works just fine. But when I make 100 buttons under ListView, I want to find them via Search Bar. But I don't know how to do it somehow.
What I want to do: I want to distinguish the buttons by filtering the word 'englishWord' among the buttons listed below. When I enter the word in 'englishWord' in Search Bar, I want the buttons containing that word to be filtered.
If I do something like below, only the texts inside are listed, not the button I made.
VocabularyWordsButton.dart
import 'package:being_moroccan/AdHelper.dart';
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:sizer/sizer.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:easy_localization/easy_localization.dart';
class VocabularyWordsButton extends StatefulWidget {
VocabularyWordsButton(
{required this.englishWord,
required this.trasncribedWord,
required this.arabicWord,
required this.sound});
final String englishWord;
final String trasncribedWord;
final String arabicWord;
final String sound;
#override
_VocabularyWordsButtonState createState() => _VocabularyWordsButtonState();
}
class _VocabularyWordsButtonState extends State<VocabularyWordsButton> {
AdHelper adHelper = AdHelper();
#override
void didChangeDependencies() {
// TODO: implement didChangeDependencies
super.didChangeDependencies();
adHelper.myLargeBanner.load();
}
bool _canShowButton = true;
void hideWidget() {
setState(() {
_canShowButton = !_canShowButton;
});
}
final AudioCache _audioCache = AudioCache(
prefix: 'audio/',
fixedPlayer: AudioPlayer()..setReleaseMode(ReleaseMode.STOP),
);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: !_canShowButton
? Column(
children: [
Container(
height: 195.h / 6,
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child: Container(
height: 100,
child: Column(
children: [
Container(
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius:
BorderRadius.all(Radius.circular(20))),
child: Center(
child: TextButton(
onPressed: () {
hideWidget();
},
child: Container(
width: MediaQuery.of(context).size.width,
child: Center(
child: Text(
widget.englishWord,
style: TextStyle(
fontSize: 30.sp / 2,
color: Colors.white),
),
),
),
),
),
),
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(
Colors.transparent),
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius:
BorderRadius.all(Radius.circular(20)),
),
),
),
onPressed: () {
print('cal');
_audioCache.play('${widget.sound}.mp3');
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(2.0),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'TRANSCRIBED'.tr(),
style: TextStyle(
fontSize: 25.sp / 2,
),
),
Container(
width:
MediaQuery.of(context).size.width /
2,
height: 60.h / 7,
child: Center(
child: Text(
widget.trasncribedWord,
style: TextStyle(
fontSize: 25.sp / 2,
),
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(2.0),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'ARABIC'.tr(),
style: TextStyle(
fontSize: 25.sp / 2,
),
),
Container(
width:
MediaQuery.of(context).size.width /
2,
height: 60.h / 7,
child: Center(
child: Text(
widget.arabicWord,
style: TextStyle(
fontSize: 25.sp / 2,
),
),
),
),
],
),
),
],
),
),
),
],
),
),
),
Container(
height: 100,
child: AdWidget(ad: adHelper.myLargeBanner),
),
],
)
: Container(
width: MediaQuery.of(context).size.width / 2,
decoration: BoxDecoration(
color: Colors.grey.withOpacity(0.1),
borderRadius: BorderRadius.all(Radius.circular(20))),
child: Center(
child: ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(Colors.transparent),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20)),
),
),
),
onPressed: () {
hideWidget();
},
child: Container(
width: MediaQuery.of(context).size.width,
child: Center(
child: Text(
widget.englishWord,
style:
TextStyle(fontSize: 30.sp / 2, color: Colors.white),
),
),
),
),
),
),
);
}
}
DictionaryScreen.dart
import 'package:sizer/sizer.dart';
import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';
import 'VocabularyWords/VocabularyWordsButton.dart';
class DictionaryScreen extends StatefulWidget {
static const String id = 'Dictionary_Screen';
const DictionaryScreen({Key? key}) : super(key: key);
#override
_DictionaryScreenState createState() => _DictionaryScreenState();
}
class _DictionaryScreenState extends State<DictionaryScreen> {
TextEditingController editingController = TextEditingController();
// final duplicateItems = List<String>.generate(10000, (i) => "Item $i");
// var items = List<String>();
List<VocabularyWordsButton> words = [
VocabularyWordsButton(
englishWord: 'To pray'.tr(),
trasncribedWord: 'Sella',
arabicWord: 'صْلّى',
sound: 'Sella',
),
VocabularyWordsButton(
englishWord: 'To prefer'.tr(),
trasncribedWord: 'Feddel',
arabicWord: 'فْضّلْ',
sound: 'Feddel',
)
];
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(),
body: Container(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
onChanged: (value) {
setState(() {});
},
controller: editingController,
decoration: InputDecoration(
labelText: "Search",
hintText: "Search",
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(25.0)))),
),
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: words.length,
itemBuilder: (context, index) {
if (editingController.text.isEmpty) {
return ListTile(
title: Text('${words[index].englishWord} '),
);
} else if (words[index]
.englishWord
.toLowerCase()
.contains(editingController.text)) {
return ListTile(
title: Text('${words[index].englishWord} '),
);
} else {
return Container();
}
}),
),
],
),
),
);
}
}

Related

Hello, I want to show the padding part at the bottom of my code on the screen with a delay of 10 seconds. How can I do it?

I want to show the padding part at the bottom of my code on the screen with a delay of 10 seconds. How can I do it?
My Code :
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_clipboard_manager/flutter_clipboard_manager.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'URL Shortener',
theme: ThemeData(
primarySwatch: Colors.purple,
),
home: StartPage(),
);
}
}
class StartPage extends StatefulWidget {
#override
_StartPageState createState() => _StartPageState();
}
class _StartPageState extends State<StartPage> {
bool visibilityTag = false;
void _changed(bool visibility, String field) {
setState(() {
if (field == "tag") {
visibilityTag = visibility;
}
});
}
final GlobalKey<ScaffoldState> _globalKey = GlobalKey<ScaffoldState>();
String shortUrl = "";
String value = "";
String buttonText = "COPY!";
bool isChanged = true;
TextEditingController urlcontroller = TextEditingController();
getData() async {
var url = 'https://api.shrtco.de/v2/shorten?url=${urlcontroller.text}';
var response = await http.get(url);
var result = jsonDecode(response.body);
if (result['ok']) {
setState(() {
shortUrl = result['result']['short_link'];
});
} else {
print(response);
}
}
copy(String url) {
FlutterClipboardManager.copyToClipBoard(url).then((value) {});
}
buildRow(String data, bool original) {
return SingleChildScrollView(
child: original
? Container(
alignment: Alignment.center,
child: Text(
data,
))
: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
data,
),
ElevatedButton(
child: Text(buttonText),
style: ElevatedButton.styleFrom(
primary: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
minimumSize: Size(300, 40),
),
onPressed: () {
copy(shortUrl);
setState(() {
if (isChanged == true) {
buttonText = "COPIED!";
}
});
},
),
],
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[300],
body: ListView(
children: [
SvgPicture.asset(
'assets/logo.svg',
),
SvgPicture.asset(
'assets/illustration.svg',
),
Center(
child: Text(
"Let's get started!",
style: TextStyle(
fontSize: 20,
color: Color.fromRGBO(53, 50, 62, 10),
fontWeight: FontWeight.bold),
),
),
Center(
child: SizedBox(
width: 200,
height: 60,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Paste your first link into the field to shorten it",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 15,
color: Color.fromRGBO(76, 74, 85, 10),
fontWeight: FontWeight.bold)),
),
),
),
SizedBox(
height: 130,
child: Stack(
alignment: Alignment.center,
children: [
Container(
alignment: Alignment.centerRight,
color: Color.fromRGBO(59, 48, 84, 1),
child: SvgPicture.asset(
'assets/shape.svg',
color: Color.fromRGBO(75, 63, 107, 1),
),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 300,
height: 40,
child: TextField(
onChanged: (text) {
value = "URL : " + text;
},
controller: urlcontroller,
textAlign: TextAlign.center,
decoration: InputDecoration(
contentPadding: EdgeInsets.all(10.0),
border: OutlineInputBorder(
borderRadius: const BorderRadius.all(
const Radius.circular(10.0),
),
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
),
fillColor: Colors.white,
filled: true,
hintText: 'Shorten a link here ...'),
),
),
SizedBox(
height: 10,
),
SizedBox(
width: 300,
child: ElevatedButton(
onPressed: getData,
style: ElevatedButton.styleFrom(
primary: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
minimumSize: Size(60, 40),
),
child: Text('SHORTEN IT!'),
),
),
],
),
],
),
),
Padding(
padding: const EdgeInsets.all(13.0),
child: Container(
color: Colors.white,
width: double.infinity,
child: Column(
children: [
SizedBox(
height: 10,
),
buildRow(value, true),
buildRow(shortUrl, false),
],
),
),
)
],
),
);
}
}
Hello, I want to show the padding part at the bottom of my code on the screen with a delay of 10 seconds. How can I do it?
Hello, I want to show the padding part at the bottom of my code on the screen with a delay of 10 seconds. How can I do it?
Hello, I want to show the padding part at the bottom of my code on the screen with a delay of 10 seconds. How can I do it?Hello, I want to show the padding part at the bottom of my code on the screen with a delay of 10 seconds. How can I do it?
On State create a bool like
bool showCopyButton = false;
Change to true at
SizedBox(
width: 300,
child: ElevatedButton(
onPressed: ()async {
print("Button Click");
await getData();
setState(() {
showCopyButton = true;
});
},
style: ElevatedButton.styleFrom(
primary: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
minimumSize: Size(60, 40),
),
child: Text('SHORTEN IT!'),
),
),
And wrap with Visibility Like
Visibility(
visible: showCopyButton,
child: Padding(
padding: const EdgeInsets.all(13.0),
child: Container(
color: Colors.white,
width: double.infinity,
child: Column(
children: [
SizedBox(
height: 10,
),
buildRow("Text ", true),
buildRow("asdad", false),
],
),
),
),
)
or you can just if like
if (showCopyButton)
Padding(
padding: const EdgeInsets.all(13.0),
child: Container(
color: Colors.white,
width: double.infinity,
child: Column(
children: [
SizedBox(
height: 10,
),
buildRow("Text ", true),
buildRow("asdad", false),
],
),
),
),
Btw you need to use await before making it true.
Hope this helps:
import 'package:flutter/material.dart';
class Screen extends StatefulWidget {
#override
_ScreenState createState() => _ScreenState();
}
class _ScreenState extends State<Screen> {
bool _paddingVisible = false;
#override
void initState() {
super.initState();
Future.delayed(const Duration(seconds: 10), () {
// Check if mounted == true, because the screen might closed
// before 10 seconds pass
if (mounted) {
// Setting padding visibility to true after 10 seconds
setState(() {
_paddingVisible = true;
});
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
// All your widgets
// When _paddingVisible becomes true it will be displayed
if (_paddingVisible) SizedBox(height: 10),
],
),
);
}
}

How to Refresh page data API get data dynamically in flutter

I used the RefreshIndicator to pull to refresh the page data but it not working
This is my code!! help me to over come the issue on refresh on data
import 'dart:async';
import 'package:apitest3/services/api_manager.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'models/statusinfo.dart';
import 'package:flutter/services.dart';
class TestPage extends StatefulWidget {
const TestPage({Key? key}) : super(key: key);
#override
_TestPageState createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
late Future<Status> _status;
final GlobalKey<RefreshIndicatorState> _refreshIndicatorkey =
new GlobalKey<RefreshIndicatorState>();
#override
void initState() {
_status = API_Manager().getStatus();
super.initState();
WidgetsBinding.instance?.addPostFrameCallback(
(_) => _refreshIndicatorkey.currentState?.show());
}
#override
Widget build(BuildContext context) {
final key = new GlobalKey<ScaffoldState>();
return Scaffold(
body: SafeArea(
child: RefreshIndicator(
key: keyStatus,
onRefresh: () => _status,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.purple, Colors.blue])),
padding: EdgeInsets.all(4),
child: FutureBuilder<Status>(
future: _status,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
padding: EdgeInsets.all(4),
itemCount: 1,
itemBuilder: (context, index) {
var result = snapshot.data!.result.syncInfo;
return Flexible(
child: Card(
elevation: 20,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Colors.indigo.shade900,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Container(
child: Text(
"Latest Block Hash ",
style: TextStyle(
fontSize: 15,
color: Colors.white),
)),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
RaisedButton.icon(
color: Colors.blueAccent,
onPressed: () {
Clipboard.setData(ClipboardData(
text: result.latestBlockHash));
key.currentState!
.showSnackBar(new SnackBar(
backgroundColor:Colors.amberAccent,
content: new Text(
"Copied to Latest Block Hash!!",
style: TextStyle(
color: Colors.red),
),
));
},
icon: Icon(
Icons.copy,
color: Colors.white,
size: 15,
),
label: Text(
"${result.latestBlockHash}",
style: TextStyle(
fontSize: 7.1,
color: Colors.white),
overflow: TextOverflow.ellipsis,
maxLines: 1,
)),
),
),
),
);
}
}
),
),
Card(
color: Colors.blueAccent,
child: Padding(
padding: const EdgeInsets.all(6.0),
child: Container(
height: 20,
child: Row(
children: [
Text(
" ${result.latestBlockTime
.toString()}",
style: TextStyle(
fontSize: 10,
color: Colors.white),
),
],
),
],
),
),
);
});
} else
return Center(child: CircularProgressIndicator()
//CupertinoActivityIndicator()
);
},
),
),
),
),
);
}
}
I don't know what i made mistake on this code for refresh function
And all so i try to root navigation method but it pop more pages on the same page so once try to close the page it there several pages to close,
so, try to help me on proper way to pull refresh on the page.
You need to update the state after refreshing on onRefresh callback. Currently, you are just assigning it to a Future variable.
This is a simple way to do it.
RefreshIndicator(
onRefresh: () { setState((){
// Update your data here
}); },
child: ...
)

How to generate new route to the new stfull widget when user created new container?

I am currently developing an app which people can save their receipt in it, I shared home screen below,initial time It will be empty, as soon as user add new menu, it will get full with menu, After user added new menu, the should be able to click the menu container, and access to new screen for example, İn home screen I created container which called "CAKES", the cakes screen should be created, if I created another menu in my home screen It should also created too, I currently menu extanded screen as a statefull widget already, you can see below, but my question is How can I create this page for spesific menu's , How can I store them, in list, in map etc, Lastly, I dont want user information dissapear, I know I have to use database, but I want to use local database, How can I handle with that, Have a nice day...
import 'package:flutter/material.dart';
import 'package:lezzet_kitabi/add_menu_screen.dart';
import 'package:lezzet_kitabi/constants.dart';
import 'package:lezzet_kitabi/widgets.dart';
class HomeScreen extends StatefulWidget {
HomeScreen({this.newMenuName,this.imagePath});
final imagePath;
final newMenuName;
static String id="homeScreen";
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
Widget buildBottomSheet(BuildContext context)=>AddMenuScreen(buttonText: "Menü Ekle",route: HomeScreen,);
void initState(){
super.initState();
if (widget.newMenuName!=null && widget.imagePath!=null){
Widget newMenu=MenuCard(newMenuName: widget.newMenuName,imagePath: widget.imagePath);
menuCards.insert(0,newMenu);
}
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: kColorTheme1,
appBar: AppBar(
centerTitle: true,
automaticallyImplyLeading: false,
elevation: 5,
backgroundColor: Color(0xFFF2C3D4).withOpacity(1),
title:TitleBorderedText(title:"SEVIMLI YEMEKLER", textColor: Color(0xFFFFFB00)),
actions: [
CircleAvatar(
radius: 27,
backgroundColor: Colors.transparent,
backgroundImage: AssetImage(kCuttedLogoPath),
),
],
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(kBGWithLogoOpacity),
fit: BoxFit.cover,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: GridView.count(
crossAxisCount: 2,
children:menuCards,
),
),
Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: EdgeInsets.all(10),
child: Container(
decoration: BoxDecoration(
boxShadow:[
BoxShadow(
color: Colors.black.withOpacity(1),
spreadRadius: 2,
blurRadius: 7,
offset: Offset(0,4),
),
],
color: kColorTheme7,
borderRadius: BorderRadius.circular(40),
),
child: FlatButton(
onPressed: (){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(buttonText: "Menü Ekle",route: "homeScreen",),
);
},
child: TitleBorderedText(title: "LEZZET GRUBU EKLE",textColor: Colors.white,)
),
),
),
],
)
],
),
),
),
);
}
}
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:lezzet_kitabi/screens/home_screen.dart';
import 'package:lezzet_kitabi/widgets.dart';
import 'constants.dart';
import 'dart:math';
class AddMenuScreen extends StatefulWidget {
AddMenuScreen({#required this.buttonText, #required this.route});
final route;
final String buttonText;
static String id="addMenuScreen";
#override
_AddMenuScreenState createState() => _AddMenuScreenState();
}
class _AddMenuScreenState extends State<AddMenuScreen> {
int selectedIndex=-1;
Color _containerForStickersInactiveColor=Colors.white;
Color _containerForStickersActiveColor=Colors.black12;
final stickerList= List<String>.generate(23, (index) => "images/sticker$index");
String chosenImagePath;
String menuName;
int addScreenImageNum;
void initState(){
super.initState();
createAddScreenImageNum();
}
void createAddScreenImageNum(){
Random random =Random();
addScreenImageNum = random.nextInt(3)+1;
}
#override
Widget build(BuildContext context) {
return Material(
child: Container(
color: kColorTheme9,
child: Container(
height: 400,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(topRight: Radius.circular(40),topLeft: Radius.circular(40)),
),
child:Padding(
padding:EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
decoration: BoxDecoration(
color: kColorTheme2,
borderRadius: BorderRadius.circular(90)
),
child: TextField(
style: TextStyle(
color: Colors.black,
fontFamily:"Graduate",
fontSize: 20,
),
textAlign: TextAlign.center,
onChanged: (value){
menuName=value;
},
decoration: InputDecoration(
border:OutlineInputBorder(
borderRadius: BorderRadius.circular(90),
borderSide: BorderSide(
color: Colors.teal,
),
),
hintText: "Menü ismi belirleyin",
hintStyle: TextStyle(
color: Colors.black.withOpacity(0.2),
fontFamily: "Graduate",
),
),
),
),
SizedBox(height: 20,),
Text(" yana kadırarak menünüz icin bir resim secin",textAlign: TextAlign.center,
style: TextStyle(fontFamily: "Graduate", fontSize: 12),),
SizedBox(height: 20,),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: stickerList.length,
itemBuilder: (context,index){
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: index == selectedIndex ?
_containerForStickersActiveColor :
_containerForStickersInactiveColor,
),
child:FlatButton(
child: Image(
image: AssetImage("images/sticker$index.png"),
),
onPressed: (){
setState(() {
selectedIndex = index;
});
},
),
);
}
),
),
SizedBox(height: 20,),
Container(
decoration: BoxDecoration(
border: Border.all(style: BorderStyle.solid),
color: kColorTheme7,
borderRadius: BorderRadius.circular(90),
),
child: FlatButton(
onPressed: (){
widget.route=="homeScreen"?Navigator.push(context, MaterialPageRoute(builder: (context)=>HomeScreen(newMenuName: menuName,imagePath: "images/sticker$selectedIndex.png")))
:Navigator.push(context, MaterialPageRoute(builder: (context)=>MenuExtension(menuExtensionName: menuName)),
);
},
child: Text(widget.buttonText, style: TextStyle(fontSize: 20, color: Colors.white,
fontFamily: "Graduate", fontWeight: FontWeight.bold),),
),
),
],
),
),
),
),
);
}
}
import 'package:flutter/material.dart';
import 'dart:math';
import 'add_menu_screen.dart';
import 'package:bordered_text/bordered_text.dart';
import 'package:lezzet_kitabi/screens/meal_screen.dart';
import 'constants.dart';
List<Widget> menuExtensionCards=[EmptyMenu()];
List<Widget> menuCards=[EmptyMenu()];
class MenuCard extends StatelessWidget {
MenuCard({this.newMenuName, this.imagePath});
final newMenuName;
final imagePath;
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top:15.0),
child: FlatButton(
onPressed: (){
Navigator.push(context, MaterialPageRoute(builder: (context)=>MenuExtension(menuExtensionName: newMenuName,)));
},
child: Container(
height: 180,
width: 180,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Color((Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(0.5),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(height: 10,),
Container(
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.5),
borderRadius: BorderRadius.circular(90),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
newMenuName,
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Graduate',
fontWeight: FontWeight.bold),
),
),
),
Expanded(
child: Padding(
padding:EdgeInsets.all(5),
child: Image(
image: AssetImage(
imagePath
),
),
),
),
],
),
),
),
);
}
}
class EmptyMenu extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top:15.0),
child: FlatButton(
onPressed: (){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(buttonText: "Menü Ekle",route:"homeScreen"),
);
},
child: Container(
height: 180,
width: 180,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Colors.black12.withOpacity(0.1),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(Icons.add_circle_outline_outlined,size: 100,color: Colors.grey.shade400,),
],
),
),
),
);
}
}
class MenuExtension extends StatefulWidget {
MenuExtension({this.menuExtensionName});
final String menuExtensionName;
#override
_MenuExtensionState createState() => _MenuExtensionState();
}
class _MenuExtensionState extends State<MenuExtension> {
Widget buildBottomSheet(BuildContext context)=>AddMenuScreen(buttonText: "Tarif Ekle",route: MealScreen,);
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
centerTitle: true,
automaticallyImplyLeading: false,
elevation: 5,
backgroundColor: Color(0xFFF2C3D4).withOpacity(1),
title:BorderedText(
child:Text(
widget.menuExtensionName,
style: TextStyle(
color: Color(0XFFFFFB00),
fontSize: 30,
fontFamily: "Graduate"
),
),
strokeWidth: 5,
strokeColor: Colors.black,
),
actions: [
CircleAvatar(
radius: 27,
backgroundColor: Colors.transparent,
backgroundImage: AssetImage("images/cuttedlogo.PNG"),
),
],
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("images/logoBGopacity.png"),
fit: BoxFit.cover,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: GridView.count(
crossAxisCount: 2,
children:menuExtensionCards,
),
),
Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: EdgeInsets.all(10),
child: Container(
decoration: BoxDecoration(
boxShadow:[
BoxShadow(
color: Colors.black.withOpacity(1),
spreadRadius: 2,
blurRadius: 7,
offset: Offset(0,4),
),
],
color: kColorTheme7,
borderRadius: BorderRadius.circular(40),
),
child: FlatButton(
onPressed: (){
showModalBottomSheet(
context: context,
builder: (BuildContext context)=> AddMenuScreen(buttonText: "Tarif Ekle", route:"mealScreen"),
);
},
child: BorderedText(
strokeWidth: 5,
strokeColor: Colors.black,
child:Text("Tarif Ekle",style: TextStyle(
color: Colors.white,
fontFamily:'Graduate',
fontSize:30,
),
),
),
),
),
),
],
)
],
),
),
),
);
}
}
class TitleBorderedText extends StatelessWidget {
TitleBorderedText({this.title, this.textColor});
final Color textColor;
final String title;
#override
Widget build(BuildContext context) {
return BorderedText(
strokeWidth: 5,
strokeColor: Colors.black,
child:Text(title,style: TextStyle(
color: textColor,
fontFamily:'Graduate',
fontSize:30,
),
),
);
}
}

Flutter: is there any possibility to send the button value to the text field?

I am Writing a small quiz game, in which I am pressing the button and these buttons are going to the empty text fields, I don't know how to send the text of the button to the text fields.
here is my code :
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: NinjaCard()));
class NinjaCard extends StatefulWidget {
#override
_NinjaCardState createState() => _NinjaCardState();
}
class _NinjaCardState extends State<NinjaCard> {
String result = "";
String shaka = "";
var text;
String str;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(title: Text('Animals'), backgroundColor: Colors.green),
body: Padding(
padding: EdgeInsets.all(15),
child: Column(
children: <Widget>[
Center(
child: Image.asset('lib/photo-1495594059084-33752639b9c3.jpg'),
),
SizedBox(width: 10, height: 10),
Row(children: <Widget>[
Container(
color: Colors.grey,
width: 40.0,
child: Text('$result', style: TextStyle(fontSize: 10.0, height: 2.0, color: Colors.black)),
),
SizedBox(width: 10),
Container(
color: Colors.grey,
width: 40.0,
child: Text('$shaka', style: TextStyle(fontSize: 10.0, height: 2.0, color: Colors.black)),
),
SizedBox(width: 15),
Row(
children: <Widget>[
SizedBox(
width: 50,
child: RaisedButton(
onPressed: () {},
color: Colors.green,
splashColor: Colors.red,
child: Text('S', style: TextStyle(backgroundColor: Colors.green, fontSize: 20, color: Colors.white)),
),
),
SizedBox(width: 15),
SizedBox(
width: 50,
child: RaisedButton(
onPressed: () {},
color: Colors.green,
splashColor: Colors.red,
child: Text('T', style: TextStyle(backgroundColor: Colors.green, fontSize: 20, color: Colors.white)),
),
),
SizedBox(width: 15),
],
),
]),
],
),
),
);
}
}
In a simple case, I would go with a stateful widget and array of letters. Of course, it could be created and sized dynamically, below I only explain the basic idea with some simplifications (no duplicate checks, no shuffling):
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'App',
home: GuessTheWordWidget(),
);
}
}
class GuessTheWordWidget extends StatefulWidget {
#override
_GuessTheWordWidgetState createState() => _GuessTheWordWidgetState();
}
class _GuessTheWordWidgetState extends State<GuessTheWordWidget> {
String _word = 'Goldfish';
List<String> _input = List.generate(8, (_) => '');
int _position = 0;
void _press(int rune) {
setState(() {
if (_position < _input.length) {
print('Position ${_position}, rune: ${String.fromCharCode(rune)}');
_input[_position++] = String.fromCharCode(rune);
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('App'),
),
body: Center(
child: Column(children: <Widget>[
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: _input
.map((letter) => Container(
margin: const EdgeInsets.all(15.0),
padding: const EdgeInsets.all(3.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.blueAccent)),
child: Text(letter),
))
.toList())),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: _word.runes
.map((rune) => RaisedButton(
onPressed: () => _press(rune),
child: Text(String.fromCharCode(rune),
style: TextStyle(fontSize: 20)),
))
.toList())),
])),
);
}
}
Go play with this code at DartPad: https://dartpad.dev/69bae58772305c74f1688193076ecaef!

Accessing a function from one to another dart class

I am new to flutter. I have class name LoginCard.dart in this I have another class named _FormPageState which have _validateInputs function `
import 'package:firstapp/Future/app_futures.dart';
import 'package:firstapp/Models/Base/EventObject.dart';
import 'package:firstapp/Widgets/SignupCard.dart';
import 'package:firstapp/utils/constants.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:firstapp/Components/ProgressDialog.dart';
class LoginCard extends StatelessWidget {
#override
Widget build (BuildContext context){
return new Container(
child: new LoginFormContainer(),
);
}
}
class LoginFormContainer extends StatefulWidget{
// #override
// _FormPageState createState() => _FormPageState();
State<StatefulWidget> createState() {
return _FormPageState();
}
}
class _FormPageState extends State<LoginFormContainer>{
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
bool _autoValidate = false;
// bool _obscureText = true;
String _email;
String _password;
ProgressDialog progressDialog = ProgressDialog
.getProgressDialog(ProgressDialogTitles.USER_LOG_IN);
#override
Widget build(BuildContext context) {
return new Container(
width: double.infinity,
height: ScreenUtil.getInstance().setHeight(500),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8.0),
boxShadow: [
BoxShadow(
color: Colors.black12,
offset: Offset(0.0, 15.0),
blurRadius: 15.0),
BoxShadow(
color: Colors.black12,
offset: Offset(0.0, -10.0),
blurRadius: 10.0),
]),
child: Padding(
padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0),
child: new Form(
key: _formKey,
autovalidate: _autoValidate,
child: new Stack(
children: <Widget>[loginFormUI(), progressDialog]
)
),
),
);
}
Widget loginFormUI(){
return new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Login",
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(45),
fontFamily: "Poppins-Bold",
letterSpacing: .6)),
SizedBox(
height: ScreenUtil.getInstance().setHeight(30),
),
Text("Username",
style: TextStyle(
fontFamily: "Poppins-Medium",
fontSize: ScreenUtil.getInstance().setSp(26))),
new TextFormField(
autofocus: true,
keyboardType: TextInputType.text,
validator: validateEmail,
onSaved: (val) =>
_email = val,
decoration: InputDecoration(
hintText: "username",
hintStyle: TextStyle(color: Colors.grey, fontSize: 12.0)),
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(30),
),
Text("Password",
style: TextStyle(
fontFamily: "Poppins-Medium",
fontSize: ScreenUtil.getInstance().setSp(26))),
new TextFormField(
obscureText: true,
keyboardType: TextInputType.text,
validator: validatePassword,
onSaved: (val) =>
_password = val,
decoration: InputDecoration(
hintText: "Password",
hintStyle: TextStyle(color: Colors.grey, fontSize: 12.0)),
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(35),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Text(
"Forgot Password?",
style: TextStyle(
color: Colors.blue,
fontFamily: "Poppins-Medium",
fontSize: ScreenUtil.getInstance().setSp(28)),
)
],
)
],
);
}
String validateEmail(String value){
Pattern pattern = r'^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regex = new RegExp(pattern);
if(value.isEmpty)
return "Email is required";
else if(!regex.hasMatch(value))
return 'Enter valid email';
else
return null;
}
String validatePassword(String value){
if (value.isEmpty)
return "Password is required";
else
return null;
}
void _validateInputs() {
if (_formKey.currentState.validate()){
print("hello");
// If all data are correct then save data to out variables
_formKey.currentState.save();
FocusScope.of(context).requestFocus(new FocusNode());
progressDialog.showProgress();
// _addNewUser();
_performLogin();
} else {
// If all data are not valid then start auto validation.
setState(() {
_autoValidate = true;
});
}
}
void _performLogin() async{
EventObject eventObject = await performLogin(_email, _password);
}
}
`
and Another class name is main.dart `
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'Widgets/LoginCard.dart';
import 'Widgets/SocialIcons.dart';
import 'CustomIcons.dart';
import 'signup.dart';
//
void main() => runApp(MaterialApp(
home: MyApp(),
debugShowCheckedModeBanner: false,
));
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _isSelected = false;
// _FormPageState formPageState;
void _radio() {
setState(() {
_isSelected = !_isSelected;
});
}
Widget radioButton(bool isSelected) => Container(
width: 16.0,
height: 16.0,
padding: EdgeInsets.all(2.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(width: 2.0, color: Colors.black)),
child: isSelected
? Container(
width: double.infinity,
height: double.infinity,
decoration:
BoxDecoration(shape: BoxShape.circle, color: Colors.black),
)
: Container(),
);
Widget horizontalLine() => Padding(
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Container(
width: ScreenUtil.getInstance().setWidth(120),
height: 1.0,
color: Colors.black26.withOpacity(.2),
),
);
#override
Widget build(BuildContext context) {
ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
ScreenUtil.instance =
ScreenUtil(width: 750, height: 1334, allowFontScaling: true);
return new Scaffold(
backgroundColor: Colors.white,
resizeToAvoidBottomPadding: true,
body: Stack(
fit: StackFit.expand,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 100.0),
child: Image.asset("assets/carscartoon.png"),
),
Expanded(
child: Container(),
),
Image.asset("assets/image_02.png")
],
),
SingleChildScrollView(
child: Padding(
padding: EdgeInsets.only(left: 28.0, right: 28.0, top: 60.0),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Image.asset(
"assets/tlrlogo.png",
width: ScreenUtil.getInstance().setWidth(110),
height: ScreenUtil.getInstance().setHeight(110),
),
Text("Transport Levy Record",
style: TextStyle(
fontFamily: "Poppins-Bold",
fontSize: ScreenUtil.getInstance().setSp(30),
letterSpacing: .6,
fontWeight: FontWeight.bold))
],
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(180),
),
LoginCard(),
SizedBox(height: ScreenUtil.getInstance().setHeight(40)),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
SizedBox(
width: 12.0,
),
GestureDetector(
onTap: _radio,
child: radioButton(_isSelected),
),
SizedBox(
width: 8.0,
),
Text("Remember me",
style: TextStyle(
fontSize: 12, fontFamily: "Poppins-Medium"))
],
),
InkWell(
child: Container(
width: ScreenUtil.getInstance().setWidth(330),
height: ScreenUtil.getInstance().setHeight(100),
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
Color(0xFF17ead9),
Color(0xFF6078ea)
]),
borderRadius: BorderRadius.circular(6.0),
boxShadow: [
BoxShadow(
color: Color(0xFF6078ea).withOpacity(.3),
offset: Offset(0.0, 8.0),
blurRadius: 8.0)
]),
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: () {
// LoginFormContainer()
},
child: Center(
child: Text("SIGNIN",
style: TextStyle(
color: Colors.white,
fontFamily: "Poppins-Bold",
fontSize: 18,
letterSpacing: 1.0)),
),
),
),
),
)
],
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(40),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
horizontalLine(),
Text("Social Login",
style: TextStyle(
fontSize: 16.0, fontFamily: "Poppins-Medium")),
horizontalLine()
],
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(40),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SocialIcons(
colors: [
Color(0xFF102397),
Color(0xFF187adf),
Color(0xFF00eaf8),
],
iconData: CustomIcons.facebook,
onPressed: () {},
),
SocialIcons(
colors: [
Color(0xFFff4f38),
Color(0xFFff355d),
],
iconData: CustomIcons.googlePlus,
onPressed: () {},
),
SocialIcons(
colors: [
Color(0xFF17ead9),
Color(0xFF6078ea),
],
iconData: CustomIcons.twitter,
onPressed: () {},
),
SocialIcons(
colors: [
Color(0xFF00c6fb),
Color(0xFF005bea),
],
iconData: CustomIcons.linkedin,
onPressed: () {},
)
],
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(30),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"New User? ",
style: TextStyle(fontFamily: "Poppins-Medium"),
),
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder:
(context) => Signup()));
},
child: Text("SignUp",
style: TextStyle(
color: Color(0xFF5d74e3),
fontFamily: "Poppins-Bold")),
)
],
)
],
),
),
)
],
),
);
}
}
`
On line No. 143 there is onTap function of SignIn button in my main.dart class, I want access _validateInputs() function of _FormPageState.
I am new in dart. Please let me know, if any solution for this.
Put _validateInputs() function and all variables in main.dart file which is used in LoginCard.dart file and pass variables to Logincard constructor as argument from main.dart file.
In main.dart file
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
pass _formkey to LoginCard() constructor
LoginCard(_formKey);
in LoginCard.dart file
class LoginCard extends StatelessWidget {
final GlobalKey<FormState> formKey;
LoginCard(this.formKey);
#override
Widget build (BuildContext context){
return new Container();
}