how to change images when clicked 2~3 toggle buttons together - flutter

https://i.stack.imgur.com/NmkxE.jpg
enter image description here
how to change images when clicked 2~3 toggle buttons together
this is what I want to make.
9cat pictures included in the example.
I want to load cat images( total 9 cat images) //clicked room1 button,cat1button -> load cat1 image // room1button,cat2button - > load cat 2 image ... clicked room3, cat3button -> load cat 9 image
enter image description here
enter code here
import '123.dart';
import '456.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('imageToggle'),),
body: Column(
children: [
Expanded(child: Image.asset('images/meow.jpg')),
Button123(),
Button456(),
],
),
),
);
}
}
class Button123 extends StatefulWidget {
#override
_Button123State createState() => _Button123State();
}
class _Button123State extends State<Button123> {
List<bool> isSelected = List.generate(3, (index) => false);
#override
Widget build(BuildContext context) {
return Container(
height: 40,
child: ToggleButtons(
isSelected: isSelected,
color: Colors.black,
fillColor: Colors.grey,
children: [
Padding(padding: const EdgeInsets.symmetric(horizontal: 2),
child: Text('room1'),),
Padding(padding: const EdgeInsets.symmetric(horizontal: 2),
child: Text('room2'),),
Padding(padding: const EdgeInsets.symmetric(horizontal: 2),
child: Text('room3'),),
],
onPressed: (int newIndex) {
setState(() {
for (int index = 0; index < isSelected.length; index++) {
if (index == newIndex) {
isSelected[index] = true;
} else {
isSelected[index] = false;
}
}
});
},
)
);
}
}

Related

Dart: Reading a specific line in a text based on a keyword

I have this line of text that is as follows:
IMEI
IMEII :869425035089513
IME12:869425035100520
SN:3ST0218A22000432
I want to only get the 2nd line of text that is "IMEII :869425035089513" but remove the rest. How shall I do that in Dart?
try this
var str = "IMEI"
IMEII :869425035089513
IME12:869425035100520
SN:3ST0218A22000432";
var parts = str.split('\n');
print(parts[0]);
print(parts[1]);// print 2nd Line data
When you enter a string in the text field, only the strings that contain the entered string are displayed.
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
//data
List<String> _list = [
'IMEI',
'IMEII :869425035089513',
'IME12:869425035100520',
'SN:3ST0218A22000432'
];
//show data
List<String> _data = [];
#override
Widget build(BuildContext context) {
Size _size = MediaQuery.of(context).size;
return Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_textFiled(_size),
for (int i = 0; i < _data.length; i++)
_showData(_size, i),
],
),
),
),
);
}
//TextFiled Widget
Widget _textFiled(Size size) {
return Container(
width: size.width,
height: size.height * 0.1,
child: TextField(
decoration: InputDecoration(
labelText: 'Text',
),
onChanged: (String text) {
_data.clear();
setState(() {
if (text.isEmpty) {
_data = _list.toList();
} else {
for (int i = 0; i < _list.length; i++) {
if (_list[i].contains(text)) {
_data.add(_list[i].toString());
}
}
}
});
},
),
);
}
//show Data
Widget _showData(Size size, int index) {
return Container(
width: size.width,
height: size.height * 0.05,
child: Text('${_data[index]}'),
);
}
}
You can use contain() which is a string comparison.

how to change an image when I click a toggle button(flutter)

enter image description here
I cannot embed image because I don't have 10 reputation.
I want to load image when I click toggle buttons. it seems simple for you but it is hard for me to do it. I am a beginner .
I don't know how to write onPressed button. I already wrote onPressed buttons for toggle button. it seems like it is not possible to write one more oppressed code. I already used the onpressedbutton code to use ToggleButton, but I need one more function to load image but I don't know how to do it
enter code here
import 'package:flutter/material.dart';
import '123.dart';
import '456.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('imageToggle'),),
body: Column(
children: [
Expanded(child: Image.asset('images/meow.jpg')),
Button123(
),
Button456(),
],
),
),
);
}
}
class Button456 extends StatefulWidget {
#override
_Button456State createState() => _Button456State();
}
class _Button456State extends State<Button456> {
List<bool> isSelected = List.generate(3, (index) => false);
#override
Widget build(BuildContext context) {
return Container(
child: ToggleButtons(
isSelected: isSelected,
color: Colors.black,
fillColor: Colors.grey,
children: [
Padding(padding: const EdgeInsets.symmetric(horizontal: 12),
child: Text('cat1'),),
Padding(padding: const EdgeInsets.symmetric(horizontal: 12),
child: Text('cat2'),),
Padding(padding: const EdgeInsets.symmetric(horizontal: 12),
child: Text('cat3'),),
],
onPressed: (int newIndexx) {
setState(() {
for (int index = 0; index < isSelected.length; index++) {
if (index == newIndexx) {
isSelected[index] = true;
} else {
isSelected[index] = false;
}
}
});
},
)
);
}
}
You can make the image url a variable.
String imageLink = 'myImage.png';
class _MyAppState extends State<MyApp> {
onButtonPressed(String value) {
setState(() {imageLink = value});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('imageToggle'),),
body: Column(
children: [
Expanded(child: Image.asset(imageLink)),
TextButton(child: Text('Click Me!'), onPressed: onButtonPressed('newImageLink')),
],
),
),
);
}
}

Flutter horizontal Listview/Pageview with selected element animated to full width

so basically I just want to have a horizontal snapping ListView or PageView with items inside, where the currently selected Item will take the whole available full width. This is my base code so far:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
// Initialize DATA MODEL list with some random values.
List<DataModel> dataList = ['Andrew', 'Test', 'Data', 'Random']
.map<DataModel>((s) => DataModel(s))
.toList();
double containerWidth;
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
//var fWidth = MediaQuery.of(context).size.height * 1;
return MaterialApp(
title: 'Adjustable height card.',
home: Scaffold(
body: ListView.builder(
controller: PageController(viewportFraction: 0.8),
scrollDirection: Axis.horizontal,
itemCount: dataList.length,
itemBuilder: (context, index) {
DataModel item = dataList.elementAt(index);
// Check if the item is expanded or not and set size accordingly
containerWidth = item.expanded
? MediaQuery.of(context).size.width * 1
: MediaQuery.of(context).size.width * 0.30;
return GestureDetector(
onDoubleTap: () {
setState(() {
item.expanded = !item.expanded;
});
},
child: AnimatedContainer(
curve: Curves.easeOut,
duration: Duration(milliseconds: 400),
color: Colors.red,
width: containerWidth,
margin: EdgeInsets.all(8),
child: Center(
child: Text(
dataList.elementAt(index).title,
style: TextStyle(
color: Colors.white,
),
),
),
),
);
},
),
));
}
}
class DataModel {
String title;
bool expanded;
DataModel(this.title) {
expanded = false;
}
}
As you can see for now I can give the selected element full width, but I need to have some kind of page snapping, because at the moment im not able to skip the big or small containers in a good way. Now If I change the whole thing to a PageView, I dont have control anymore about the width of AnimatedContainer. Please help.
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
// Initialize DATA MODEL list with some random values.
List<DataModel> dataList = ['Andrew', 'Test', 'Data', 'Random']
.map<DataModel>((s) => DataModel(s))
.toList();
double containerWidth;
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Adjustable height card.',
home: Scaffold(
body: ListView(children: getViewList(),controller: PageController(viewportFraction: 0.8),
scrollDirection: Axis.horizontal,)
));
}
List<Widget> getViewList()
{
var listOfWidgets = List<Widget>();
for (var item in dataList) {
containerWidth = item.expanded
? MediaQuery.of(context).size.width* 1
: MediaQuery.of(context).size.width * 0.30;
listOfWidgets.add(GestureDetector(
onDoubleTap: () {
print("onDoubleTap");
setState(() {
for (var item in dataList)
item.expanded=false;
item.expanded = !item.expanded;
});
},
child: AnimatedContainer(
curve: Curves.easeOut,
duration: Duration(milliseconds: 100),
color: Colors.red,
width: containerWidth,
margin: EdgeInsets.all(8),
child: Center(
child: Text(
item.title,
style: TextStyle(
color: Colors.white,
),
),
),
),
)); // TODO: Whatever layout you need for each widget.
}
return listOfWidgets;
}
}
class DataModel {
String title;
bool expanded;
DataModel(this.title) {
expanded = false;
}
}

how Can i make this Single selection Flutter?

I have an Apps which is having a listview with the reaction button in a flutter . I want to make this when a user clicked any of this love icon then it's filled with red color.
enter image description here
enter image description here
Like this image but the problem is when I clicked one of this love icon all of the icons turned into red color but I only want to change the color of love of icon which one is Selected.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool like;
#override
List<String> user = ['Dipto', 'Dipankar', "Sajib", 'Shanto', 'Pranto'];
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ListView Demu'),
),
body: Center(
child: Container(
child: ListView.builder(
itemCount: user.length,
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.all(10),
height: 50,
width: MediaQuery.of(context).size.width * 0.8,
color: Colors.yellowAccent,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
user[index],
),
Positioned(
child: IconButton(
icon: _iconControl(like),
onPressed: () {
if (like == false) {
setState(() {
like = true;
_iconControl(like);
});
} else {
setState(() {
like = false;
_iconControl(like);
});
}
},
),
),
],
),
);
},
),
)),
);
}
_iconControl(bool like) {
if (like == false) {
return Icon(Icons.favorite_border);
} else {
return Icon(
Icons.favorite,
color: Colors.red,
);
}
}
}
I also try with using parameter but Its failed Like that :
child: IconButton(
icon: _iconControl(true),
onPressed: () {
if (false) {
setState(() {
_iconControl(true);
});
} else {
setState(() {
_iconControl(false);
});
}
},
),
Can you help me Please. Thanks in advance
You can create a modal class to manage the selection of your list
Just create a modal class and add a boolean variable to maintaining selection using. that boolean variable
SAMPLE CODE
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool like;
List<Modal> userList = List<Modal>();
#override
void initState() {
userList.add(Modal(name: 'Dipto', isSelected: false));
userList.add(Modal(name: 'Dipankar', isSelected: false));
userList.add(Modal(name: 'Sajib', isSelected: false));
userList.add(Modal(name: 'Shanto', isSelected: false));
userList.add(Modal(name: 'Pranto', isSelected: false));
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ListView Demu'),
),
body: Center(
child: Container(
child: ListView.builder(
itemCount: userList.length,
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.all(10),
height: 50,
width: MediaQuery
.of(context)
.size
.width * 0.8,
color: Colors.yellowAccent,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
userList[index].name,
),
Positioned(
child: IconButton(
icon: _iconControl( userList[index].isSelected),
onPressed: () {
setState(() {
userList.forEach((element) {
element.isSelected = false;
});
userList[index].isSelected = true;
});
},
),
),
],
),
);
},
),
)),
);
}
_iconControl(bool like) {
if (like == false) {
return Icon(Icons.favorite_border);
} else {
return Icon(
Icons.favorite,
color: Colors.red,
);
}
}
}
class Modal {
String name;
bool isSelected;
Modal({this.name, this.isSelected = false});
}

How to create sticky shop button animation in Flutter?

How can I create this sticky buy button animation of Adidas app in Flutter. I have tried to use a scroll controller to listen for the position of user and then use an animated container but it is of no use since I have to define my scroll controller in my initstate while the height of my containers are relative to my device's height.
here is the link of video for the animation:
https://drive.google.com/file/d/1TzIUBr6abRQI87xAVu4NOPG67aftzceK/view?usp=sharing
this is what the widget tree looks like:
Scaffold(appbar,FAB,_body),
_body= SingleChildSrollView child:Column[Container(child:Listview)
,Container(child:PageView(children:[GridView])
,Container
,Container(this is where the shop button should be, the one that replaces the FAB)
,GridView,])
Output:
void main() => runApp(MaterialApp(home: Scaffold(body: HomePage(), appBar: AppBar())));
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
ScrollController _controller = ScrollController();
double _boxHeight = 200, _screenHeight;
int _itemIndex = 5;
bool _itemVisibility = true;
#override
void initState() {
super.initState();
double offsetEnd;
WidgetsBinding.instance.addPostFrameCallback((_) {
RenderBox box = context.findRenderObject();
_screenHeight = box.globalToLocal(Offset(0, MediaQuery.of(context).size.height)).dy;
offsetEnd = ((_itemIndex + 1) - (_screenHeight / _boxHeight)) * _boxHeight;
});
_controller.addListener(() {
if (_controller.position.pixels >= offsetEnd) {
if (_itemVisibility) setState(() => _itemVisibility = false);
} else {
if (!_itemVisibility) setState(() => _itemVisibility = true);
}
});
}
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
ListView.builder(
controller: _controller,
itemCount: 8,
itemBuilder: (context, index) {
return _buildBox(
index: index,
color: index == _itemIndex ? Colors.cyan : Colors.blue[((index + 1) * 100) % 900],
);
},
),
Positioned(
bottom: 0,
right: 0,
left: 0,
child: Visibility(
visible: _itemVisibility,
child: _buildBox(index: _itemIndex, color: Colors.cyan),
),
),
],
);
}
Widget _buildBox({int index, Color color}) {
return Container(
height: _boxHeight,
color: color,
alignment: Alignment.center,
child: Text(
"${index}",
style: TextStyle(fontSize: 52, fontWeight: FontWeight.bold),
),
);
}
}
Another answer (variable height boxes)
void main() => runApp(MaterialApp(home: Scaffold(body: HomePage(), appBar: AppBar())));
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
ScrollController _controller = ScrollController();
double _screenHeight, _hRatings = 350, _hSize = 120, _hWidth = 130, _hComfort = 140, _hQuality = 150, _hBuy = 130, _hQuestions = 400;
bool _itemVisibility = true;
#override
void initState() {
super.initState();
double offsetEnd;
WidgetsBinding.instance.addPostFrameCallback((_) {
RenderBox box = context.findRenderObject();
_screenHeight = box.globalToLocal(Offset(0, MediaQuery.of(context).size.height)).dy;
offsetEnd = (_hRatings + _hSize + _hWidth + _hComfort + _hQuality + _hBuy) - _screenHeight;
});
_controller.addListener(() {
if (_controller.position.pixels >= offsetEnd) {
if (_itemVisibility) setState(() => _itemVisibility = false);
} else {
if (!_itemVisibility) setState(() => _itemVisibility = true);
}
});
}
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
ListView(
controller: _controller,
children: <Widget>[
_buildBox(_hRatings, "Ratings box", Colors.blue[200]),
_buildBox(_hSize, "Size box", Colors.blue[300]),
_buildBox(_hWidth, "Width box", Colors.blue[400]),
_buildBox(_hComfort, "Comfort box", Colors.blue[500]),
_buildBox(_hQuality, "Quality box", Colors.blue[600]),
_buildBox(_hBuy, "Buy box", Colors.orange[700]),
_buildBox(_hQuestions, "Questions part", Colors.blue[800]),
],
),
Positioned(
bottom: 0,
right: 0,
left: 0,
child: Visibility(
visible: _itemVisibility,
child: _buildBox(_hBuy, "Buy box", Colors.orange[700]),
),
),
],
);
}
Widget _buildBox(double height, String text, Color color) {
return Container(
height: height,
color: color,
alignment: Alignment.center,
child: Text(
text,
style: TextStyle(
fontSize: 32,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
);
}
}
I would show a floatingActionButton when the embedded button is not visible. Here's a solution based on this thread : How to know if a widget is visible within a viewport?
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() => new MyAppState();
}
class MyAppState extends State<MyApp> {
GlobalKey<State> key = new GlobalKey();
double fabOpacity = 1.0;
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text("Scrolling."),
),
body: NotificationListener<ScrollNotification>(
child: new ListView(
itemExtent: 100.0,
children: [
ContainerWithBorder(),
ContainerWithBorder(),
ContainerWithBorder(),
ContainerWithBorder(),
ContainerWithBorder(),
ContainerWithBorder(),
ContainerWithBorder(),
ContainerWithBorder(),
new MyObservableWidget(key: key),
ContainerWithBorder(),
ContainerWithBorder(),
ContainerWithBorder(),
ContainerWithBorder(),
ContainerWithBorder(),
ContainerWithBorder(),
ContainerWithBorder()
],
),
onNotification: (ScrollNotification scroll) {
var currentContext = key.currentContext;
if (currentContext == null) return false;
var renderObject = currentContext.findRenderObject();
RenderAbstractViewport viewport = RenderAbstractViewport.of(renderObject);
var offsetToRevealBottom = viewport.getOffsetToReveal(renderObject, 1.0);
var offsetToRevealTop = viewport.getOffsetToReveal(renderObject, 0.0);
if (offsetToRevealBottom.offset > scroll.metrics.pixels ||
scroll.metrics.pixels > offsetToRevealTop.offset) {
if (fabOpacity != 1.0) {
setState(() {
fabOpacity = 1.0;
});
}
} else {
if (fabOpacity == 1.0) {
setState(() {
fabOpacity = 0.0;
});
}
}
return false;
},
),
floatingActionButton: new Opacity(
opacity: fabOpacity,
child: Align(
alignment: Alignment.bottomCenter,
child: new FloatingActionButton.extended(
label: Text('sticky buy button'),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4.0)),
onPressed: () {
print("YAY");
},
),
),
),
),
);
}
}
class MyObservableWidget extends StatefulWidget {
const MyObservableWidget({Key key}) : super(key: key);
#override
State<StatefulWidget> createState() => new MyObservableWidgetState();
}
class MyObservableWidgetState extends State<MyObservableWidget> {
#override
Widget build(BuildContext context) {
return new RaisedButton(
onPressed: () {
},
color: Colors.lightGreenAccent,
child: Text('This is my buy button', style: TextStyle(color: Colors.blue),),
);
}
}
class ContainerWithBorder extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Container(
decoration: new BoxDecoration(border: new Border.all(), color: Colors.grey),
);
}
}