How to create a favorite buton in hive flutter? - flutter

I am trying to create a favorite button for my app. Which work is to change and save color, while the user presses it, So I decided to use hive db for it. When the icon button is tapped; the color get changed, which indicates to the user that it's been marked as their favorite. The problem is when I tap it again(if the user wants to unmark it ) though the color get changed ,when i move to other page or hot start/reload the page, the color changed back to it former self automatically(To the color when it was first pressed).I want the color reactive through the button and be saved. How can I solve this issue?(I am kinda confused at the key part. Maybe that's where the problem occurred)
class p1 extends StatefulWidget {
#override
_p1State createState() => _p1State();
}
class _p1State extends State<p1> {
Box box;
bool _isFavorite = false;
_p1State();
#override
void initstate(){
super.initState();
// Get reference to an already opened box
box = Hive.box(FAVORITES_BOX);
final data = box.get(_isFavorite).containskey("1" != null ? Colors.white:Colors.red );
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body:Stack(
children:<Widget>[
Image(
image:AssetImage("Image/Chowsun1.jpg"),
fit:BoxFit.cover,
width: double.infinity,
height: double.infinity,
),
Align(alignment: Alignment.center,
child: Text(' "\n The entire world , \n is not worth \n A single Tear.\n'
' " \n -Imam Hazrat Ali (R) '
,style: TextStyle(fontSize: 35.0,
color: Colors.white,
fontFamily: "Explora",
fontWeight: FontWeight.w900 ) )
),
Stack ( children: [Positioned(
top:90,
right: 20,
child:const Text(' 1 ',
style: TextStyle(
fontSize: 25.0,
color: Colors.white,
fontFamily: "Comforter"
),
),
)], ),
Align(
alignment: Alignment.bottomCenter,
child: (
IconButton(
icon: Icon(
Icons.favorite,
color:_isFavorite ? Colors.white: Colors.red
),
onPressed: () {
setState(() {
_isFavorite= !_isFavorite;
});
if(box.containsKey(1)){
box.delete(1);
}else
box.put(1, _isFavorite);
}
)
)
)])
),
);
}
}

I see you're using a bool _isFavorite to record a like, and then you check for the value of is favorite again to know if to give a like or remove the like, well under the hood your hive is working but basically, the code you're using to update the color is not coming from the hive so when you reupdate your state, e.g Hot Reload everything is reset to the initial leaving your favorite button unchanged.
You basically just need to re-model your logic for it to work properly.
import 'package:hive_flutter/hive_flutter.dart';
void main() async {
await Hive.initFlutter();
await Hive.openBox("favorites");
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Box? box = Hive.box("favorites");
bool _isFavorite = false;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Stack(
children: <Widget>[
Align(
alignment: Alignment.center,
child: Text(
' "\n The entire world , \n is not worth \n A single Tear.\n'
' " \n -Imam Hazrat Ali (R) ',
style: TextStyle(
fontSize: 35.0,
color: Colors.white,
fontFamily: "Explora",
fontWeight: FontWeight.w900),
),
),
Stack(
children: [
Positioned(
top: 90,
right: 20,
child: const Text(
' 1 ',
style: TextStyle(
fontSize: 25.0,
color: Colors.white,
fontFamily: "Comforter"),
),
)
],
),
Align(
alignment: Alignment.bottomCenter,
child: (IconButton(
icon: Icon(Icons.favorite,
color: box!.isEmpty ? Colors.white : Colors.red),
onPressed: () {
setState(() {
_isFavorite = !_isFavorite;
});
if (box!.isEmpty)
box!.put("isFavorite", _isFavorite);
else
box!.delete("isFavorite");
},
)),
)
],
),
),
);
}
}

You can directly initialize hive while it is already open
Box box = Hive.box(FAVORITES_BOX);
bool _isFavorite = false;
#override
void initState() {
super.initState();
_isFavorite = box.get(0) ?? false;
}
And changing value
onPressed: () {
setState(() {
_isFavorite = !_isFavorite;
});
box.put(0, _isFavorite);
},

Related

Flutter - RichText not appear when called

I'm fairly new to Flutter,
I created this script where the Accuracy function adds green TextSpan to the AccuracySpeech list if the spoken word is present in the text string or otherwise it is red.
The script seems to work, the only problem is that I would like once it finishes listening, the Accuracy() function is called and the RichText() appears on the screen (currently the Accuracy() function is called, but the RichText does not appear).
Anyone know how I can fix and make the RichText appear?
import 'dart:core';
import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:speech_to_text/speech_to_text.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
SpeechToText _speechToText = SpeechToText();
bool _speechEnabled = false;
String _lastWords = '';
#override
void initState() {
super.initState();
_initSpeech();
}
/// This has to happen only once per app
void _initSpeech() async {
_speechEnabled = await _speechToText.initialize();
setState(() {});
}
/// Each time to start a speech recognition session
void _startListening() async {
AccuracySpeech.clear();
await _speechToText.listen(onResult: _onSpeechResult);
setState(() {});
}
/// Manually stop the active speech recognition session
/// Note that there are also timeouts that each platform enforces
/// and the SpeechToText plugin supports setting timeouts on the
/// listen method.
void _stopListening() async {
await _speechToText.stop();
Accuracy(_lastWords, text);
setState(() {});
}
/// This is the callback that the SpeechToText plugin calls when
/// the platform returns recognized words.
void _onSpeechResult(SpeechRecognitionResult result) {
setState(() {
_lastWords = result.recognizedWords;
});
}
String text = 'Hi, my name is Gabriele';
List<TextSpan> AccuracySpeech = [];
void Accuracy(String _lastWords, String text) {
var lastWordsSplitted = _lastWords.toLowerCase().split(' ');
var textSplitted = text.toLowerCase().split(' ');
print(lastWordsSplitted);
for (String word in lastWordsSplitted) {
if (textSplitted.contains(word)) {
AccuracySpeech.add(
TextSpan(text: word + ' ', style: TextStyle(color: Colors.green)),
);
} else {
AccuracySpeech.add(
TextSpan(text: word + ' ', style: TextStyle(color: Colors.red)),
);
}
}
print(AccuracySpeech);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Speech Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(child: Text(text)),
Container(
padding: EdgeInsets.all(16),
child: Text(
'Recognized words:',
style: TextStyle(fontSize: 20.0),
),
),
Expanded(
child: Container(
padding: EdgeInsets.all(16),
child: Text(
// If listening is active show the recognized words
_speechToText.isListening
? '$_lastWords'
// If listening isn't active but could be tell the user
// how to start it, otherwise indicate that speech
// recognition is not yet ready or not supported on
// the target device
: _speechEnabled
? 'Tap the microphone to start listening...'
: 'Speech not available',
),
),
),
// Todo: Make RichText appear on the screen when stop listening
Expanded(
child: Center(
child: RichText(
text: TextSpan(
style: TextStyle(fontSize: 18.0),
children: AccuracySpeech,
),
),
),
),
/// Listen Button
Center(
child: Container(
child: RawMaterialButton(
onPressed: _speechToText.isNotListening
? _startListening
: _stopListening,
child: Icon(
_speechToText.isNotListening ? Icons.mic_off : Icons.mic,
size: 27,
color: Colors.white,
),
elevation: 0,
shape: CircleBorder(),
constraints: BoxConstraints.tightFor(
width: 48.0,
height: 48.0,
),
),
decoration: BoxDecoration(
color: Color(0xFF25BBC2),
borderRadius: BorderRadius.circular(40.0),
),
),
),
],
),
),
);
}
}
Hope someone can help me.
Thank you :)

How to save icon color in hive flutter?

I am trying to create a favorite button for my app. Which work is to change and save color, while the user presses it,So I decided to use hive db for it.When the icon button is tapped; the color get changed,which indicates the user that its been marked as their favorite.The problem is when i tap it again(if the user wants to unmark it ) though the color get changed ,when i move to other page or hot start/reload the page, the color changed back to it former self automatically(To the color when it was first pressed).I wants the color reactive through the button and be saved.How can i solve this issue?
class p1 extends StatefulWidget {
#override
_p1State createState() => _p1State();
}
class _p1State extends State<p1> {
Box box;
bool _isFavorite = false;
_p1State();
#override
void initstate(){
super.initState();
// Get reference to an already opened box
box = Hive.box(FAVORITES_BOX);
final data = box.get(_isFavorite);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body:Stack(
children:<Widget>[
Image(
image:AssetImage("Image/Chowsun1.jpg"),
fit:BoxFit.cover,
width: double.infinity,
height: double.infinity,
),
Align(alignment: Alignment.center,
child: Text(' Rehman '
,style: TextStyle(fontSize: 35.0,
color: Colors.white,
fontFamily: "Explora",
fontWeight: FontWeight.w900 ) )
),
Stack ( children: [Positioned(
top:90,
right: 20,
child:const Text(' 1 ',
style: TextStyle(
fontSize: 25.0,
color: Colors.white,
fontFamily: "Comforter"
),
),
)], ),
Align(
alignment: Alignment.bottomCenter,
child: (
IconButton(
icon: Icon(
Icons.favorite,
color:_isFavorite ? Colors.white: Colors.red
),
onPressed: () {
setState(() {
_isFavorite= !_isFavorite;
});
box.put(1, _isFavorite);
}
)
)
)])
),
);
}
}
try:
Hive.box('your_Hive_DB_Name').containsKey(
"Key" ? Colors.red: Colors.white)

A value of type 'Widget' can't be assigned to a variable of type 'PreferredSizeWidget'

THERE ARE 2 ERRORS IN THIS PROGRAM WHICH HAVE BEEN SHOWN IN THE IMAGES ABOVE
Main.dart file
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Personal Expenses ',
theme: ThemeData(
primarySwatch: Colors.green,
accentColor: Colors.amber,
//errorColor: Colors.red[700],
fontFamily: 'Quicksand',
textTheme: ThemeData.light().textTheme.copyWith(
title: TextStyle(
fontFamily: 'OpenSans',
fontWeight: FontWeight.bold,
fontSize: 18,
),
button: TextStyle(color: Colors.amber)),
appBarTheme: AppBarTheme(
textTheme: ThemeData.light().textTheme.copyWith(
title: TextStyle(
fontFamily: 'OpenSans',
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final List<Transaction> _userTransactions = [
];
bool _showChart = false;
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) {
final mediaQuery = MediaQuery.of(context);
final isLandscape = mediaQuery.orientation == Orientation.landscape;
final PreferredSizeWidget appbar = Platform.isIOS
A value of type 'Widget' can't be assigned to a variable of type 'PreferredSizeWidget'.
? CupertinoNavigationBar(
middle: Text(
'Personal Expenses ',
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
GestureDetector(
child: Icon(CupertinoIcons.add),
onTap: () => _startAddNewTransaction(context),
)
],
),
)
: AppBar(
title: Text(
'Personal Expenses ',
style: TextStyle(fontFamily: 'OpenSans'),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () => _startAddNewTransaction(context),
),
],
);
final txListWidget = Container(
height: (mediaQuery.size.height -
appbar.preferredSize.height -
mediaQuery.padding.top) *
0.7,
child: TransactionList(
_userTransactions,
_deleteTransaction,
),
);
final pageBody = SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
if (isLandscape)
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Show Chart'),
Switch.adaptive(
activeColor: Theme.of(context).accentColor,
value: _showChart,
onChanged: (val) {
setState(() {
_showChart = val;
});
},
),
],
),
],
),
);
return Platform.isIOS
? CupertinoPageScaffold(
child: pageBody,
navigationBar: appbar,
The argument type 'PreferredSizeWidget' can't be assigned to the parameter type 'ObstructingPreferredSizeWidget?'.
)
: Scaffold(
.........,
),
);
}
}
Your code works in non-null safe versions of Flutter. I do not know why the null safe version now objects to:
final PreferredSizeWidget appbar = Platform.isIOS ...
If you omit the type:
final appbar = Platform.isIOS ...
Then appbar is interpreted as a Widget and gives an error on appbar.preferredSize.
You can force the type to be examined at runtime:
final dynamic appbar = Platform.isIOS ...
This works for me testing with my Android device. However, I have not tested with an Apple device.
I created this flutter issue for the change in behaviour with the null-safe version of flutter. You can subscribe to the issue to get update notifications.
Edit:
The Flutter team raised a Dart issue which explains the new bahaviour and suggests using:
final PreferredSizeWidget appbar = (Platform.isIOS ? CupertinoNavigationBar() : AppBar())
as PreferredSizeWidget;
I faced the same issue, this is due to the null safety feature of Dart
Solution
final dynamic appBar = Platform.isIOS
? CupertinoNavigationBar() : AppBar()
Or you can use
final PreferredSizedWidget appBar = Platform.isIOS
? CupertinoNavigationBar() as ObstructingPreferredSizedWidget : AppBar()
the issue is , appBar accept widget that implements PreferredSize
and CupertinoPageScaffold accept widget the implements ObstructingPreferredSizeWidget
so don't determine the datatype of the appbar
and let it be determine at the runtime
simply make it like this
final appBar = Platform.IOS ? CupertinoNavigationBar() : AppBar()
and add the CupertinoNavigationBar in CupertinoPageScaffold
and add the AppBar in Scaffold

build method runs before initState finishes

I'm trying to make a weather app with Flutter. But for some reason, the build() method runs before the initState() method finishes. The thing is, all the state variables are initialized using the setState() method inside the initState(), whose variables are to be used in build() method. I guess the problem is that Flutter is trying to access those state variables before the setState() method, which keeps throwing me the error: A non-null String must be provided to a Text widget. I know these codes are too long to read. But I'd appreciate it if you could help me with this.
import 'package:flutter/material.dart';
import "package:climat/screens/LoadingScreen.dart";
import "package:climat/screens/MainScreen.dart";
import "package:climat/screens/SearchScreen.dart";
void main() {
runApp(
MaterialApp(
theme: ThemeData(
fontFamily: "Open Sans",
),
title: "Climat",
initialRoute: "/",
onGenerateRoute: (RouteSettings routeSettings) {
dynamic routes = <String, WidgetBuilder>{
"/": (context) => LoadingScreen(),
"/index": (context) => MainScreen(),
"/search": (context) => SearchScreen(),
};
WidgetBuilder builder = routes[routeSettings.name];
return MaterialPageRoute(builder: (context) => builder(context));
},
),
);
}
import "package:flutter/material.dart";
import "package:flutter_spinkit/flutter_spinkit.dart";
import "package:climat/services/GeolocatorHelper.dart";
import "package:climat/services/NetworkHelper.dart";
import "package:climat/utilities/constants.dart";
class LoadingScreen extends StatefulWidget {
#override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
Future<void> getWeatherData() async {
Map<String, double> coordinates = await GeolocatorHelper().getGeoData();
final NetworkHelper networkHelper = NetworkHelper(
uri:
"$endPoint&lat=${coordinates["latitude"]}&lon=${coordinates["longitude"]}");
final dynamic data = await networkHelper.getData();
return await Navigator.pushNamed(context, "/index", arguments: data);
}
#override
void initState() {
this.getWeatherData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Climat"),
),
body: SafeArea(
child: Center(
child: SpinKitRing(
color: Colors.redAccent,
),
),
),
);
}
}
import "package:flutter/material.dart";
import "package:climat/services/WeatherHelper.dart";
import "package:climat/services/NetworkHelper.dart";
import "package:climat/utilities/constants.dart";
class MainScreen extends StatefulWidget {
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
Color backgroundColor;
String cityName;
int temperature;
String status;
String image;
int minTemperature;
int maxTemperature;
int humidity;
Future<void> updateUI({String userInput = null}) async {
dynamic weatherData;
if (userInput == null) {
weatherData = ModalRoute.of(context).settings.arguments;
} else {
final NetworkHelper networkHelper =
NetworkHelper(uri: "$endPoint&q=$userInput");
weatherData = await networkHelper.getData();
}
final int weatherCode = weatherData["weather"][0]["id"];
final WeatherHelper weatherHelper = WeatherHelper(
weatherCode: weatherCode,
);
setState(() {
this.backgroundColor = weatherHelper.getBackgroundColor();
this.cityName = weatherData["name"];
this.temperature = weatherData["main"]["temp"].toInt();
this.status = weatherHelper.getWeatherStatus();
this.minTemperature = weatherData["main"]["temp_min"].toInt();
this.maxTemperature = weatherData["main"]["temp_max"].toInt();
this.humidity = weatherData["main"]["humidity"];
this.image = weatherHelper.getWeatherImage();
});
}
#override
void initState() {
this.updateUI();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: this.backgroundColor,
appBar: AppBar(
title: Text("Climat"),
),
body: SafeArea(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
this.cityName,
style: TextStyle(
fontSize: 24.0,
color: Colors.white,
),
),
SizedBox(
height: 30.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
"./assets/images/${this.image}",
scale: 4.0,
),
SizedBox(
width: 30.0,
),
Text(
"${this.temperature}°C",
style: TextStyle(
fontSize: 96.0,
color: Colors.white,
),
),
],
),
SizedBox(
height: 30.0,
),
Text(
this.status.toUpperCase(),
style: TextStyle(
fontSize: 24.0,
color: Colors.white,
),
),
SizedBox(
height: 10.0,
),
Text(
"MIN / MAX : ${this.minTemperature.toString()} / ${this.maxTemperature.toString()}",
style: TextStyle(
fontSize: 24.0,
color: Colors.white,
),
),
SizedBox(
height: 10.0,
),
Text(
"HUMIDITY : ${this.humidity}%",
style: TextStyle(
fontSize: 24.0,
color: Colors.white,
),
),
SizedBox(
height: 30.0,
),
ElevatedButton(
onPressed: () async {
dynamic userInput =
await Navigator.pushNamed(context, "/search");
this.updateUI(
userInput: userInput.toString(),
);
},
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(
vertical: 8.0,
horizontal: 16.0,
),
),
child: Text(
"Search by city name",
style: TextStyle(
fontSize: 20.0,
),
),
),
],
),
),
),
);
}
}
if you want to use Future function in initState and want it run once and complete before build, please consider to use WidgetsBinding.instance.addPostFrameCallback, like
#override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) async {
await this.getWeatherData();
setState(() { });
});
}
and
#override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) async {
await this.updateUI();
setState(() { });
});
}
setState should be used for rebuild the widget

Having trouble with my horizontal scroll - flutter

I hope you are doing well today. I'm having an issue with this horizontal scroll in flutter. The images are supposed to scroll left and right and depending on the picture, you will press the button and have the ability to guess the type of pic. For some reason, images and tags don't match with images. The image names are linked to the vehicleNames list in _MyHomePageState. I have also included image_card.dart to show how ImageCard works. Thank you for the second set of eyes.
main.dart
import 'dart:ui';
import 'package:flutter/material.dart';
import 'image_card.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Guess the car!'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin{
String curVehName = "";
double scrollPercent = 0.0;
Offset startDrag;
double startDragPercentScroll;
double finishScrollStart;
double finishScrollEnd;
AnimationController finishScrollController;
List<String> vehicleNames = [
'bmw',
'ford',
'rover',
'toyota'
];
#override
initState(){
super.initState();
finishScrollController = AnimationController(
duration: Duration(milliseconds: 150),
vsync: this,
)..addListener(() {
setState(() {
scrollPercent = lerpDouble(finishScrollStart, finishScrollEnd,
finishScrollController.value);
});
});
#override
dispose(){
finishScrollController.dispose();
super.dispose();
}
}
List<Widget> buildCards(){
List<Widget> cardList = [];
for(int i = 0; i < vehicleNames.length;i++){
cardList.add(buildCard(i,scrollPercent));
print("index: ${i}");
}
return cardList;
}
Widget buildCard(int cardIndex, double scrollPercent){
final cardScrollPercent = scrollPercent / ( 1 / vehicleNames.length);
return FractionalTranslation(
translation: Offset(cardIndex-cardScrollPercent,0.0),
child: Padding(
padding: EdgeInsets.all(8.0),
child: ImageCard(imageName: vehicleNames[cardIndex],
),
),
);
}
onHorizontalDragStart(DragStartDetails details){
startDrag = details.globalPosition;
startDragPercentScroll = scrollPercent;
}
onHorizontalDragUpdate(DragUpdateDetails details){
final currentDrag = details.globalPosition;
final dragDistance = currentDrag.dx - startDrag.dx;
final singleCardDragPercent = dragDistance / context.size.width;
setState(() {
scrollPercent = ( startDragPercentScroll + ( -singleCardDragPercent
/ vehicleNames.length)).clamp(0.0, 1.0-(1/vehicleNames.length));
});
}
onHorizontalDragEnd(DragEndDetails details){
finishScrollStart = scrollPercent;
finishScrollEnd = (scrollPercent * vehicleNames.length).round()
/vehicleNames.length;
finishScrollController.forward(from: 0.0);
setState(() {
startDrag = null;
startDragPercentScroll = null;
curVehName = '';
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
GestureDetector(
onHorizontalDragStart: onHorizontalDragStart,
onHorizontalDragUpdate: onHorizontalDragUpdate,
onHorizontalDragEnd: onHorizontalDragEnd,
behavior: HitTestBehavior.translucent ,
child: Stack(
children: buildCards(),
),
),
OutlineButton(
padding: EdgeInsets.all(10.0),
onPressed: (){
setState((){
this.curVehName = vehicleNames[(scrollPercent*10).round()];
});
},
child: Text(
'Show Answer',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
borderSide: BorderSide(
color: Colors.black,
width: 4.0,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
highlightedBorderColor: Colors.black,
),
Text(
curVehName,
style: TextStyle(
fontSize: 40,
fontWeight: FontWeight.bold,
color: Colors.blue,
letterSpacing: 2,
),
),
],
),
),
);
}
}
image_card.dart
import 'package:flutter/material.dart';
class ImageCard extends StatelessWidget{
final String imageName;
ImageCard({this.imageName});
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
border: Border.all(
color: Colors.black,
width: 4.0,
),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Image.asset(
'assets/images/$imageName.jpg',
height: 300,
fit: BoxFit.fitHeight,
),
),
);
}
}
I believe I found the issue. It seems that the
this.curVehName = vehicleNames[(scrollPercent*10).round()];
hard-coded the value of numbers needed in my vehicle names list. Once I added 10 pictures and added names to the list, it then worked as directed. The goal now is to see if I can make this a dynamic list.