how to check which element was tapped in flutter and dat - flutter

I created a list of widgets. What I would like to do is to get the index of the widget that is being tapped. I wrapped the widget in gesture detection, and I would like to print the index of the widget which is being tapped
This is a widget I created:
class Tile extends StatelessWidget {
final Color color;
const Tile({Key? key,required this.color}) : super(key: key);
sayhello(int idd){
print("Hello from the tile file$idd");
}
#override
Widget build(BuildContext context) {
return GestureDetector(
child: Container(
width: 30,
height: 31,
color: color,
),
);
}
}
This is the file where it is being used:
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
List<Widget> list = [
Tile(color: Colors.black26),
Tile(color: Colors.cyanAccent),
Tile(color: Colors.deepOrange),
Tile(color: Colors.tealAccent),
Tile(color: Colors.purpleAccent),
Tile(color: Colors.yellowAccent),
Tile(color: Colors.black),
];
Color color=Colors.amber;
void _incrementCounter() {
setState(() {
if(true)
{
list[0]=Container(
child: Text('HN'),
color: Colors.deepOrange,
);
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children:[
Row(
children: [
list[0],
list[1],
list[2],
],
),
Row(
children: [
list[3],
list[4],
list[5],
],
),
]
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
I created a list of my widget and added the gestureDetector. I want to get the index of the widget which is being tapped.

I recommend you to use widget key.
Then you can print it on widget tap.
Code:
Tile widget
.
GestureDetector(
onTap: () {
print(
key.toString(),
);
},
child: Container(
width: 30,
height: 31,
color: color,
),
),
Calling Tile widget
List<Widget> list = [
Tile(
color: Colors.black26,
key: Key('tile_black'),
),
Tile(
color: Colors.cyanAccent,
key: Key('cyan_accent'),
),
];

Related

How do i switch Appbar title and child content with state-management in flutter?

I have a problem i have been struggling to get done for a day now
I want to dynamically switch appbar from this :
to this :
when a button is pressed.
The button is situated in the scaffold bottomNavigationBar of the first appbar widget.
I will give the code snippet of this particular widget.
I tried creating an entirely different widget and set the button onTap function to route to the new widget created.
This is not a suitable solution for me as i wish to just change state of the appbar as to avoid the weird transition when changing pages.
Also please note that the second image has a leading button that would enable the user to go back to the previous appbar.
How do i achieve this?
THIS IS THE CODE SNIPPET
import 'package:flutter/material.dart';
class CustomersView extends StatefulWidget {
#override
State<CustomersView> createState() => _CustomersViewState();
}
class _CustomersViewState extends State<CustomersView> {
List<String> items = [
"All",
"Inactive",
"One time",
"Loyal",
"Active",
];
int current = 0;
List<DropdownMenuItem<String>> get dropdownItems {
List<DropdownMenuItem<String>> menuItems = [
DropdownMenuItem(
child: Text(
"Today",
),
value: "Today"),
];
return menuItems;
}
#override
Widget build(BuildContext context) {
//final controller = Get.put(EServicesController());
return Scaffold(
appBar: AppBar(
toolbarHeight: 60,
backgroundColor: Colors.white,
title: Text(
"Customers".tr,
style: GoogleFonts.poppins(
color: Color(0xff000000),
fontSize: 20,
fontWeight: FontWeight.w600),
),
actions: [
SearchButtonWidget(),
SettingsButtonWidget(),
],
centerTitle: false,
elevation: 0,
automaticallyImplyLeading: false,
leadingWidth: 15,
// leading: new IconButton(
// icon: new Icon(Icons.arrow_back_ios, color: Color(0xff3498DB)),
// onPressed: () => {Get.back()},
// ),
),
body: RefreshIndicator(
onRefresh: () async {
// Get.find<LaravelApiClient>().forceRefresh();
// await controller.refreshNotifications(showMessage: true);
// Get.find<LaravelApiClient>().unForceRefresh();
},
child: ListView(
primary: true,
children: <Widget>[
mainHeader(),
SizedBox(
height: 10,
),
CustomersCategoriesBuilder(current: current),
],
),
),
//floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
bottomNavigationBar: current == 0 ? SizedBox() : MessageCustomersButton(),
);
}
//Button that controls the appbar state
class MessageCustomersButton extends StatelessWidget {
const MessageCustomersButton({
Key key,
this.value = false,
}) : super(key: key);
final bool value;
#override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: FadeInDown(
child: MaterialButton(
onPressed: () {
//this is the new page route ( unsatisfied approach )
Get.toNamed(Routes.MESSAGE_CUSTOMERS);
},
color: Color(0xff34495E),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.18),
),
padding: EdgeInsets.symmetric(horizontal: 30, vertical: 10),
minWidth: double.infinity,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.chat,
size: 18,
color: Colors.white,
),
SizedBox(
width: 10,
),
Text(
'Message Customers',
style: GoogleFonts.poppins(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w600),
),
],
),
),
),
),
);
}
}
Try creating the widget for AppBar only and handle the different states of AppBar there only by passing a flag like isSecondStyleAppBar then in your CustomersView widget, handle the flag using setState
class CustomAppBar extends StatelessWidget {
final bool isSecondStyleAppBar;
const CustomAppBar(this.isSecondStyleAppBar, {Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const AppBar();
}
}

Flutter scrollable layout with dynamic child

I want to create a generic Layout which accepts a child Widget as a parameter, that lays out the content as follows:
I have an AppBar at the Top, a Title (headline), and below that the Content (could be anything). At the bottom, I have a Column with a few buttons. If the content is too big for the screen, all those widgets, except the AppBar, are scrollable. If the content fits the screen, the title and content should be aligned at the top, and the buttons at the bottom.
To showcase what I mean, I created a drawing:
It is easy to create to scrollable content functionality. But I struggle with laying out the content so that the buttons are aligned at the bottom, if the content does NOT need to be scrollable.
It is important to say that I don't know the height of the content widget or the buttons. They are dynamic and can change their height. Also, the title is optional and can have two different sizes.
What I tried is the following:
import 'package:flutter/material.dart';
class BaseScreen extends StatelessWidget {
final String? title;
final bool bigHeader;
final Widget child;
final Widget bottomButtons;
const BaseScreen({
Key? key,
required this.child,
required this.bottomButtons,
this.bigHeader = true,
this.title,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final AppBar appBar = AppBar(
title: Text("AppBar"),
);
double minChildHeight = MediaQuery.of(context).size.height -
MediaQuery.of(context).viewInsets.bottom -
MediaQuery.of(context).viewInsets.top -
MediaQuery.of(context).viewPadding.bottom -
MediaQuery.of(context).viewPadding.top -
appBar.preferredSize.height;
if (title != null) {
minChildHeight -= 20;
if (bigHeader) {
minChildHeight -= bigHeaderStyle.fontSize!;
} else {
minChildHeight -= smallHeaderStyle.fontSize!;
}
}
final Widget content = Column(
mainAxisSize: MainAxisSize.min,
children: [
if (title != null)
Text(
title!,
style: bigHeader ? bigHeaderStyle : smallHeaderStyle,
textAlign: TextAlign.center,
),
if (title != null)
const SizedBox(
height: 20,
),
ConstrainedBox(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
child,
bottomButtons,
],
),
constraints: BoxConstraints(
minHeight: minChildHeight,
),
),
],
);
return Scaffold(
appBar: appBar,
body: SingleChildScrollView(
child: content,
),
);
}
TextStyle get bigHeaderStyle {
return TextStyle(fontSize: 20);
}
TextStyle get smallHeaderStyle {
return TextStyle(fontSize: 16);
}
}
The scrolling effects work perfectly, but the Buttons are not aligned at the bottom. Instead, they are aligned directly below the content. Does anyone know how I can fix this?
DartPad you can check here
customscrollview tutorial
Scaffold(
// bottomNavigationBar: ,
appBar: AppBar(
title: Text(" App Bar title ${widgets.length}"),
),
//============
body: CustomScrollView(
slivers: [
SliverFillRemaining(
hasScrollBody: false,
child: Column(
// controller: _mycontroller,
children: [
title,
...contents,
// ---------------------This give Expansion and button get down --------
Expanded(
child: Container(),
),
// ---------------------This give Expansion and button get down --------
Buttons
],
),
)
],
))
We can Achieve with the help of CustomScrollView widget and Expanded widget.here Expanded widget just expand between the widget
Sample Code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(debugShowCheckedModeBanner: false, home: MyApp()),
);
}
class MyApp extends StatefulWidget {
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
var widgets = [];
var _mycontroller = ScrollController();
#override
Widget build(BuildContext context) {
var title = Center(
child: Text(
"Scrollable title ${widgets.length}",
style: TextStyle(fontSize: 30),
));
var contents = [
...widgets,
];
var Buttons = Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 100,
child: ElevatedButton(
onPressed: () {
setState(() {
widgets.add(Container(
height: 100,
child: ListTile(
title: Text(widgets.length.toString()),
subtitle: Text("Contents BTN1"),
),
));
});
// _mycontroller.jumpTo(widgets.length * 100);
},
child: Text("BTN1"),
),
),
)),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 100,
child: ElevatedButton(
onPressed: () {
setState(() {
if (widgets.length > 0) {
widgets.removeLast();
}
});
// _mycontroller.jumpTo(widgets.length * 100);
},
child: Text("BTN2"),
),
),
))
],
);
return MaterialApp(
debugShowCheckedModeBanner: false,
home: SafeArea(
child: Scaffold(
// bottomNavigationBar: ,
appBar: AppBar(
title: Text(" App Bar title ${widgets.length}"),
),
body: CustomScrollView(
slivers: [
SliverFillRemaining(
hasScrollBody: false,
child: Column(
// controller: _mycontroller,
children: [
title,
...contents,
Expanded(
child: Container(),
),
Buttons
],
),
)
],
)),
),
);
}
}
Try this:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: BaseScreen(
bottomButtons: [
ElevatedButton(onPressed: () {}, child: const Text('Button 1')),
ElevatedButton(onPressed: () {}, child: const Text('Button 2')),
],
content: Container(
color: Colors.lightGreen,
height: 200,
),
title: 'Title',
),
);
}
}
class BaseScreen extends StatelessWidget {
final bool bigHeader;
final List<Widget> bottomButtons;
final String? title;
final Widget content;
const BaseScreen({
this.bigHeader = true,
required this.bottomButtons,
required this.content,
this.title,
});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('AppBar'),
),
body: CustomScrollView(
slivers: [
SliverFillRemaining(
hasScrollBody: false,
child: Column(
children: [
if (title != null)
Padding(
padding: const EdgeInsets.symmetric(vertical: 12),
child: Text(
title!,
style: bigHeader ? _bigHeaderStyle : _smallHeaderStyle,
textAlign: TextAlign.center,
),
),
content,
const Spacer(),
...bottomButtons,
],
),
),
],
),
);
}
TextStyle get _bigHeaderStyle => const TextStyle(fontSize: 20);
TextStyle get _smallHeaderStyle => const TextStyle(fontSize: 16);
}
Screenshots:
without_scrolling
scrolled_up
scrolled_down

error [Get] the improper use of a GetX has been detected. using bottomNavigationBar

I'm trying to implement a bottomNavigationBar, but I can't finish it, I'm using Get to handle the routes and the state of the application.
I'm new to flutter, but reading the documentation I still don't understand
This is the main widget.
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
backgroundColor: AppColors.black,
title: Center(
child: CommonAssetImage(
asset: 'logo.png',
color: AppColors.white,
height: 30,
),
),
),
body: BodyTabsScreen(),
bottomNavigationBar: HomeScreenBottomNavigatorBar()),
);
}
then,I have this widget where call other widget.In this widget I using Obs.
class HomeScreenBottomNavigatorBar extends StatelessWidget {
const HomeScreenBottomNavigatorBar({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Material(
elevation: 10,
color: AppColors.white,
child: Container(
height: 60,
padding: const EdgeInsets.symmetric(horizontal: 27),
color: AppColors.white,
child: Obx(() {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TabsScreenBottomNavigationTab(
isActive: true,
label: 'Buy',
icon: Icons.home,
onTap: () {}),
TabsScreenBottomNavigationTab(
label: 'My account',
// icon: IkramIcons.user,
// iconSize: 20,
icon: (Icons.home),
onTap: () {}),
],
);
}),
),
);
}
}
class TabsScreenBottomNavigationTab extends StatelessWidget {
final String label;
final IconData icon;
final Widget image;
final VoidCallback onTap;
final bool isActive;
final double iconSize;
const TabsScreenBottomNavigationTab({
Key key,
this.label,
this.icon,
this.image,
this.onTap,
this.isActive,
this.iconSize = 20,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final _inactiveTextStyle = Theme.of(context).textTheme.bodyText2;
final _activeTextStyle =
_inactiveTextStyle.copyWith(color: AppColors.white);
const _commonDuration = Duration(milliseconds: 200);
final _availableSpace = MediaQuery.of(context).size.width - 27 * 2;
final _inactiveWidth = _availableSpace * .2;
final _activeWidth = _availableSpace * .35;
return AnimatedContainer(
duration: _commonDuration,
width: isActive ? _activeWidth : _inactiveWidth,
height: 35,
child: Material(
color: Colors.transparent,
shape: const StadiumBorder(),
clipBehavior: Clip.antiAlias,
child: AnimatedContainer(
duration: _commonDuration,
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
child: AnimatedDefaultTextStyle(
style: isActive ? _activeTextStyle : _inactiveTextStyle,
duration: _commonDuration,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (icon != null)
Icon(
icon,
size: iconSize,
color: isActive ? AppColors.white : AppColors.black,
),
if (image != null) image,
if (isActive)
Container(
margin: const EdgeInsets.only(left: 8),
child: Text(label),
)
],
),
),
),
),
),
),
);
}
}
Getx will always throw that error when you use Obx or Getx widget without inserting an observable variable that widget. So if you are NOT trying to rebuild a widget based on an updated value of a variable that lives inside a class that exends GetxController, then don't use a Getx widget.
If you're just trying to use Getx for routing, then make sure to change your MaterialApp to GetMaterialApp and define your routes, like so.
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return GetMaterialApp(
home: Page1(),
getPages: [
GetPage(name: Page1.id, page: () => Page1()), // add: static const id = 'your_page_name'; on each page to avoid using raw strings for routing
GetPage(name: Page2.id, page: () => Page2()),
],
);
}
}
Then in the onTap of your bottom navigation bar just use
Get.to(Page2());
Just remove the Obx widget wrapping your Row widget like this:
class HomeScreenBottomNavigatorBar extends StatelessWidget {
const HomeScreenBottomNavigatorBar({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Material(
elevation: 10,
color: AppColors.white,
child: Container(
height: 60,
padding: const EdgeInsets.symmetric(horizontal: 27),
color: AppColors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TabsScreenBottomNavigationTab(
isActive: true,
label: 'Buy',
icon: Icons.home,
onTap: () {}),
TabsScreenBottomNavigationTab(
label: 'My account',
// icon: IkramIcons.user,
// iconSize: 20,
icon: (Icons.home),
onTap: () {}),
],
);
),
);
}
}
Why? Because you are not using any observable (obs/Rx) variable in your widget tree which would trigger a rebuild when the value changes. So GetX is complaining and for good reason.
The controller should be inside Obx other wise its shows this error.
LeaderBoardController controller = Get.put(getIt<LeaderBoardController>());
Obx(()=>controller.leadBoardModel != null
? Column(
children: [
Container(
height: 180,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
LeadBoardImage(type: LEADTYPE.NORMAL),
LeadBoardImage(type: LEADTYPE.CROWN),
LeadBoardImage(type: LEADTYPE.NORMAL)
]),
),
Expanded(
flex: 4,
child: ListView(
padding: EdgeInsets.symmetric(horizontal: 10.w),
children: [
for (int i = 4; i < controller.leadBoardModel!.data.result.length; i++)
LeaderBoardListItem(result:controller.leadBoardModel!.data.result[i])
],
),
)
],
)
: LoadingContainer()),
It happens when you don't use your controller value in your widget. That's why it gives error because there is no sense in using Obx or Getx() widget
MainController controller = Get.find();
return Obx(
()
{
return Column(
children: [
Text("My pretty text")
],
);
}
);
Solution :
MainController controller = Get.find();
Obx(
()
{
return Column(
children: [
Text(controller.text)
],
);
}
);
Please note that there are two required aspects: 1) extending from a GetXController, and 2) The field/method returning a value from the controller, must be computed from a Rx type. In my case, I made a sub-class of a GetXController for a test, and the return value was hard-coded (not based on a Rx value), and the ObX error occurred.
For Current Scenario You dont need to use getx for this page
(Its not proper Implementation) . please remove the OBX() your error will gone .
class HomeScreenBottomNavigatorBar extends StatelessWidget {
const HomeScreenBottomNavigatorBar({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Material(
elevation: 10,
color: AppColors.white,
child: Container(
height: 60,
padding: const EdgeInsets.symmetric(horizontal: 27),
color: AppColors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TabsScreenBottomNavigationTab(
isActive: true,
label: 'Buy',
icon: Icons.home,
onTap: () {}),
TabsScreenBottomNavigationTab(
label: 'My account',
// icon: IkramIcons.user,
// iconSize: 20,
icon: (Icons.home),
onTap: () {}),
],
);
}),
),
}

Overlay pinched image above everything

I'm trying to overlay an image during max scaling (I'm using the class InteractiveViewer) on top of other objects (also the status bar). Basically like on Instagram. I couldn't find anything reading the docs. A hint on how to proceed?
child: InteractiveViewer(
transformationController: controller,
maxScale: 2.0,
minScale: 2.0,
child: imageBig,
fit: BoxFit.fitWidth,
),
According to this issue on flutter repository:
https://github.com/flutter/flutter/issues/66111
You can achive that by using OverlayEntry Class, which will handle the rendering of your InteractiveViewer child widget over the other widgets.
Also, you can find here a code snippet for InteractiveViewerOverlay widget, that you can use directly inside your project.
https://gist.github.com/zzterrozz/623531eef065a31470e85175c744c986
created by:
https://github.com/PixelToast
https://github.com/zzterrozz
Edited:
Here is an example for the InteractiveViewerOverlay widget and how to use it.
First, the InteractiveViewerOverlay widget
class InteractiveViewerOverlay extends StatefulWidget {
final Widget child;
final double maxScale;
const InteractiveViewerOverlay({
Key key,
#required this.child,
this.maxScale,
}) : super(key: key);
#override
_InteractiveViewerOverlayState createState() =>
_InteractiveViewerOverlayState();
}
class _InteractiveViewerOverlayState extends State<InteractiveViewerOverlay>
with SingleTickerProviderStateMixin {
var viewerKey = GlobalKey();
Rect placeholder;
OverlayEntry entry;
var controller = TransformationController();
Matrix4Tween snapTween;
AnimationController snap;
#override
void initState() {
super.initState();
snap = AnimationController(vsync: this);
snap.addListener(() {
if (snapTween == null) return;
controller.value = snapTween.evaluate(snap);
if (snap.isCompleted) {
entry.remove();
entry = null;
setState(() {
placeholder = null;
});
}
});
}
#override
void dispose() {
snap.dispose();
super.dispose();
}
Widget buildViewer(BuildContext context) {
return InteractiveViewer(
key: viewerKey,
transformationController: controller,
panEnabled: false,
maxScale: widget.maxScale ?? 2.5,
child: widget.child,
onInteractionStart: (details) {
if (placeholder != null) return;
setState(() {
var renderObject =
viewerKey.currentContext.findRenderObject() as RenderBox;
placeholder = Rect.fromPoints(
renderObject.localToGlobal(Offset.zero),
renderObject
.localToGlobal(renderObject.size.bottomRight(Offset.zero)),
);
});
entry = OverlayEntry(
builder: (context) {
return Positioned.fromRect(
rect: placeholder,
child: buildViewer(context),
);
},
);
Overlay.of(context).insert(entry);
},
onInteractionEnd: (details) {
snapTween = Matrix4Tween(
begin: controller.value,
end: Matrix4.identity(),
);
snap.value = 0;
snap.animateTo(
1,
duration: Duration(milliseconds: 250),
curve: Curves.ease,
);
});
}
#override
Widget build(BuildContext context) {
var viewer = placeholder != null
? SizedBox.fromSize(size: placeholder.size)
: buildViewer(context);
return Container(
child: viewer,
);
}
}
Next, An example of implementing the InteractiveViewerOverlay widget.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(),
body: ListView(children: [
Column(
children: [
Container(
decoration: BoxDecoration(
color: Colors.white,
border:
Border(bottom: BorderSide(color: Colors.green))),
width: double.infinity,
height: 60,
child: Column(children: [
Text('Abdelazeem Kuratem',
style: TextStyle(color: Colors.black)),
Text('5 min', style: TextStyle(color: Colors.black)),
])),
InteractiveViewerOverlay(
child: Image.network(
"https://upload.wikimedia.org/wikipedia/commons/6/6a/Mona_Lisa.jpg",
fit: BoxFit.contain,
),
),
Container(
decoration: BoxDecoration(
color: Colors.grey[50],
border: Border(top: BorderSide(color: Colors.green))),
child: Stack(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_createBottomButton(
text: 'Like',
icon: Icons.thumb_up,
onPressed: () {}),
_createBottomButton(
text: 'Comment',
icon: Icons.comment,
onPressed: () {}),
_createBottomButton(
text: 'Share',
icon: Icons.share,
onPressed: () {}),
],
),
],
),
),
],
),
])),
);
}
Widget _createBottomButton({
String text,
IconData icon,
Null Function() onPressed,
}) {
return FlatButton.icon(
onPressed: onPressed,
icon: Icon(
icon,
color: Colors.green,
size: 21,
),
label: Text(
text,
style: TextStyle(color: Colors.green, fontSize: 14),
),
);
}
}

Flutter :- How to display dynamic widgets on screen?

I want to show entered text in scrambled form. ie, each letter of the word need to display in individual Container in a row. For this, I am taking text input, storing it in List<String> and then scrambling it using shuffle() and then using List.generate to return Container with Text, as below:
List<Widget> _generateJumble(String input) {
inputList = input.split('');
var shuffleList = inputList.toList()..shuffle();
print(shuffleList);
return List<Widget>.generate(shuffleList.length, (int index) {
return Container(
width: 50,
color: Colors.blue,
child: Text(shuffleList[index].toString(),
style: TextStyle(color: Colors.white),
)
);
});
}
I am calling above method onTap of a button upon which the scrambled form of the input should be displayed. But I am not sure how to display the result of above method in UI. How should I use this method so that the returning Container based on shuffleList.length will be displayed in UI as below ?
RaisedButton(
onPressed: () {},
child: Text('Clear'),
)
],
),
),
Row(
children: <Widget>[
// ? _displayJumble()
]
)
This is my solution:
1) Press a button, scrable the string and set it to the a list
2) setState and show the list to the user
This is the widget code:
class _MyHomePageState extends State<MyHomePage> {
List<String> inputList = [];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Wrap(
children: inputList.map((s) {
return Container(
width: 50,
color: Colors.blue,
child: Text(
s,
style: TextStyle(color: Colors.white),
),
);
}).toList(),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
_generateJumble('Random string');
});
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
List<Widget> _generateJumble(String input) {
inputList = input.split('');
inputList = inputList.toList()..shuffle();
print(inputList);
}
}
I used the widget Wrap because automatically wrap the widget when there is no space available for it. You can use whatever you like to use.
This is the screen result:
Before press the button:
After press the button:
Please check the below solution of it, I have used the Wrap widget for it
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutterlearningapp/colors.dart';
class HomeScreen extends StatefulWidget {
var inputVales;
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _HomeScreen();
}
}
class _HomeScreen extends State<HomeScreen> {
List<String> charcaterArray = new List<String>();
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text("Home"),
),
body: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.all(10.0),
child: TextField(
decoration: InputDecoration(labelText: 'Enter Words'),
onChanged: (text) {
setState(() {
widget.inputVales = text;
charcaterArray.clear();
for (var i = 0; i < widget.inputVales.length; i++) {
var character = widget.inputVales[i];
if (character != " ") {
charcaterArray.add(character);
}
}
});
},
),
),
Wrap(
spacing: 6.0,
runSpacing: 6.0,
children:
List<Widget>.generate(charcaterArray.length, (int index) {
return Container(
height: MediaQuery.of(context).size.height * 0.1,
width: MediaQuery.of(context).size.width * 0.1,
decoration: BoxDecoration(
color: Colors.lightGreen,
borderRadius: BorderRadius.all(Radius.elliptical(4.0, 4.0)),
),
child: Center(
child: Text(
charcaterArray[index],
style:
TextStyle(color: Colors.deepOrange, fontSize: 20.0),
),
),
);
/*Chip(
label: Text(charcaterArray[index]),
onDeleted: () {
setState(() {
charcaterArray.removeAt(index);
});
},
);*/
}),
)
],
));
}
}
And here is the output of it