Flutter: Error in syncfusion slider while applying theme - flutter

I am implementing a SFSlider in my app. When I try to give a theme to the slider using SfTheme, I get an error:
RenderBox was not laid out: _RenderSlider#850b3 relayoutBoundary=up7 'package:flutter/src/rendering/box.dart': Failed assertion: line 2009 pos 12: 'hasSize'
My code is :
Container(
height: constraints.maxHeight*0.1,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: SfTheme(
data: SfThemeData(
sliderThemeData: SfSliderThemeData(
activeLabelStyle: TextStyle(color: Colors.white),
inactiveLabelStyle: TextStyle(color: Colors.white),
)
),
child: SfSlider(activeColor: Colors.green,
inactiveColor: Colors.grey,
min: 0.0,
max: 100.0,
value: _value,
interval: 25,
showTicks: true,
showLabels: true,
enableTooltip: true,
minorTicksPerInterval: 1,
onChanged: (dynamic value) async {
totalAmount = await calculateData();
totalAmount = totalAmount.ceil() + 0.0;
setState(() {
_value = value;
total_amount_display = totalAmount;
});
},
),),),),
The Container is inside a column, which in turn is inside a container in dialog box.
When I remove the theme, the slider is rendered perfectly.

You can overcome this issue by setting color and fontSize when setting the text style for the active and inactive labels in SfSliderThemeData.
SfTheme(
data: SfThemeData(
sliderThemeData: SfSliderThemeData(
activeLabelStyle: const TextStyle(color: Colors.red, fontSize: 14),
inactiveLabelStyle: const TextStyle(color: Colors.red, fontSize: 14),
)
),
)
If you like to set the color alone for the label,then you can use the textTheme’s text style values retrieved from context’s ThemeData and using the copyWith() method to set the desired color.
final ThemeData themeData = Theme.of(context);
SfTheme(
data: SfThemeData(
sliderThemeData: SfSliderThemeData(
activeLabelStyle: themeData.textTheme.bodyText1!.copyWith(color: Colors.red),
inactiveLabelStyle: themeData.textTheme.bodyText1!.copyWith(color: Colors.red),
)
),
)
Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/i4007071991344175

Related

Flutter Tab Controller Page Navigation Error

I am making an app and I working on the onboarding screen. When the user finishes answering their questions, I want them the screen to navigate to their user dashboard. I am using a tab controller for the onboarding screen setup, and the problem that I am facing is the final screen not navigating when it is pressed.
I receive the following error when I press the button:
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: 'package:flutter/src/material/tab_controller.dart': Failed assertion: line 181 pos 12: 'value >= 0 && (value < length || length == 0)': is not true.
My code is set up to check if the tab controller index is on the last page. I understand why it is coming up as false; however, I do not know how else to code it to overcome this issue. I appreciate any help given :)
Code for button and tab controller:
class CustomButton extends StatelessWidget {
final TabController tabController;
const CustomButton({Key? key,
required this.tabController})
: super(key: key);
#override
Widget build(BuildContext context) {
return DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
color: Colors.white
),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 16),
elevation: 0,
primary: Colors.transparent
),
onPressed: () async{
if (tabController.index == 4) {
Navigator.pushNamed(context, '/dashboard');
}
else {
tabController.animateTo(tabController.index + 1);
}
// await context.read<SignupCubit>().signupWithCredentials();
User user = User(
id: context.read<SignupCubit>().state.user!.uid,
name: '',
age: 0,
imageUrls: [],
Goals: '',
Interests: [],
Focus: []);
},
child: Container(
width: double.infinity,
child: Center(
child: Text('Continue',
style: GoogleFonts.montserrat(
color: const Color.fromARGB(255, 20, 83, 106),
fontSize: 19,
fontWeight: FontWeight.w600
),),
),
)
),
);
}
}
where is your tabbarview ?
try this steps https://www.woolha.com/tutorials/flutter-using-tabbar-tabbarview-examples
or if you want to understand and implement try this
https://youtu.be/apqVp-UjsLg

Pie chart issues in flutter

I'm using the fl_chart package to create an interactive Pie Chart for my application. Although the design came out fine, I'm facing the following issues with the functionality:
Tapping on a particular PieChartSectionData doesn't always select it and even tapping repeatedly doesn't help. It's always two out of the three that are tappable. Please note that the functionality works as it should for all the sections but there is no indication suggesting that the section tapped on was clicked. As defined in my code, every tap on a section should increase the radius and it's font size to make it stand out from the rest.
Every time a PieChartSectionData is clicked, it is supposed to navigate to a new page after a delay of 500 milliseconds. Although this works as expected, I cannot seem to come back to the previous page that has the Pie Chart on it using the phone's back button on the very first click. It is only after repeated clicks that it takes me back to the original page.
The chart seems to be clickable even beyond the PieChartSectionData. So like let's say if I tap an inch away from one of the sections, it tends to take me to that other page I need to navigate to. This shouldn't be the case.
Here is my code:
class ToDoListPieState extends State<ToDoListPie> {
int? index;
double? percent;
int? taskCount;
#override
Widget build(BuildContext context) {
final provider = Provider.of<TodaysTaskList>(context).getToDoList;
// TODO: implement build
return Stack(
children: [
PieChart(PieChartData(
borderData: FlBorderData(show: false),
pieTouchData: PieTouchData(
touchCallback: (FlTouchEvent event, pieTouchResponse) {
setState(() {
if (pieTouchResponse == null ||
pieTouchResponse.touchedSection == null) {
index = -1;
}
index = pieTouchResponse!.touchedSection!.touchedSectionIndex;
});
Future.delayed(const Duration(milliseconds: 500), () {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => TaskList())); //This here is the event where clicking on a section should take us to the next page
});
print('Index: $index'); //This prints even if we click away from a section
},
),
sectionsSpace: 5,
centerSpaceRadius: 80,
sections: [
PieChartSectionData(
color: Colors.blue,
title: provider['upcoming'].length.toString(),
value: double.parse(provider['upcoming'].length.toString()),
radius: index == 0 ? 40 : 30,
titleStyle: TextStyle(fontSize: index == 0 ? 25 : 16)),
PieChartSectionData(
color: Colors.amber,
title: provider['today'].length.toString(),
value: double.parse(provider['today'].length.toString()),
radius: index == -1 ? 40 : 30,
titleStyle: TextStyle(fontSize: index == -1 ? 25 : 16)),
PieChartSectionData(
color: Colors.red,
title: provider['previous'].length.toString(),
value: double.parse(provider['previous'].length.toString()),
radius: index == 1 ? 40 : 30,
titleStyle: TextStyle(fontSize: index == 1 ? 25 : 16))
])),
Positioned(
left: 0,
top: SizeVariables.getHeight(context) * 0.18,
right: 0,
bottom: 0,
child: Column(
children: [
FittedBox(
fit: BoxFit.contain,
child: Text(
'${provider['upcoming'].length + provider['today'].length + provider['previous'].length}',
style: Theme.of(context)
.textTheme
.bodyText1!
.copyWith(fontSize: 25),
),
),
Text(
'Tasks',
style: Theme.of(context)
.textTheme
.bodyText1!
.copyWith(fontSize: 18),
)
],
),
)
],
);
}
}
Any help will be appreciated!

Obscure text bool value is not updating in flutter

I am using pin_code_text_field package to create pin code textfields. But when I was updating the bool value used to obscure text. Bool value is not updating in pin code fields until I click on textfields.
Code was added below:
bool pinWasObscured = true;
Row(
children: [
PinCodeTextField(
maxLength: 4,
hideCharacter: pinWasObscured,
highlight: true,
highlightAnimation: true,
highlightAnimationBeginColor: Colors.black,
highlightAnimationEndColor: Colors.white,
highlightAnimationDuration: Duration(seconds: 5),
highlightColor: Color(0xFFF37021),
pinBoxDecoration: ProvidedPinBoxDecoration.underlinedPinBoxDecoration,
maskCharacter: "*",
pinTextStyle: TextStyle(
fontSize: 15.sp,
fontWeight: FontWeight.bold,
),
pinBoxWidth: SizeConfig.blockSizeHorizontal! * 12,
pinBoxHeight: SizeConfig.blockSizeHorizontal! * 10,
autofocus: false,
controller: pinController,
defaultBorderColor: Colors.black26,
),
SizedBox(width: 10),
IconButton(
icon: pinWasObscured
? Icon(Icons.visibility_off_outlined)
: Icon(Icons.visibility_outlined),
onPressed: () {
setState(() {
pinWasObscured = !pinWasObscured;
});
},
),
],
),
the issue is that you are also updating the value of the "hideCharacter" on the click of item. you dont have to update the hideCharacter value everytime.
instead you have to set the value to true if you want to hide the character and false to show.

Can a single TextField in flutter have variable line height?

I'm implementing a simple rich text editor that renders text with a text editing controller that recognises basic markdown syntax, I'll link some code down below.
Everything works fine, the only problem I'm having is when a text style requires a bigger line height, for instance an # h1 that should be rendered as a title and therefore require a bigger line height overlaps over the previous line, as you can see in the screenshot below.
I've not been able so far to make the line height in a TextView variable based on the style of the text that is being displayed, is such thing even achievable in a Flutter TextView?
Here's a snippet of my text editing controller and a screenshot detailing my problem.
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class AddNotePage extends StatelessWidget {
final TextEditingController _controller = MarkdownTextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add Note'),
),
body: GestureDetector(
onVerticalDragDown: (_) {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
child: TextField(
style: defaultTextStyle,
controller: _controller,
decoration: InputDecoration(
hintText: "Insert your message",
border: UnderlineInputBorder(
borderSide: BorderSide.none,
),
),
scrollPadding: EdgeInsets.all(20.0),
keyboardType: TextInputType.multiline,
maxLines: null,
),
),
],
),
),
);
}
}
const Map<String, TextStyle> defaultMarkdownStyleMap = {
r'^# .*?$': TextStyle(
fontWeight: FontWeight.bold,
fontSize: 50,
),
r'^## .*?$': TextStyle(
fontWeight: FontWeight.bold,
fontSize: 40,
),
r'^### .*?$': TextStyle(
fontWeight: FontWeight.bold,
fontSize: 30,
),
r'__(.*?)\__': TextStyle(fontStyle: FontStyle.italic, fontSize: 20),
r'~~(.*?)~~': TextStyle(decoration: TextDecoration.lineThrough, fontSize: 20),
r'\*\*(.*?)\*\*': TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
};
const TextStyle defaultTextStyle = TextStyle(fontSize: 20);
class MarkdownTextEditingController extends TextEditingController {
final Map<String, TextStyle> styleMap;
final Pattern pattern;
MarkdownTextEditingController({this.styleMap = defaultMarkdownStyleMap})
: pattern = RegExp(
styleMap.keys.map((key) {
return key;
}).join('|'),
multiLine: true);
#override
TextSpan buildTextSpan(
{required BuildContext context,
TextStyle? style,
required bool withComposing}) {
final List<InlineSpan> children = [];
text.splitMapJoin(
pattern,
onMatch: (Match match) {
TextStyle? markdownStyle = styleMap[styleMap.keys.firstWhere(
(e) {
return RegExp(e).hasMatch(match[0]!);
},
)];
children.add(TextSpan(
text: match[0],
style: style!.merge(markdownStyle),
));
return "";
},
onNonMatch: (String text) {
children
.add(TextSpan(text: text, style: style!.merge(defaultTextStyle)));
return "";
},
);
return TextSpan(style: style, children: children);
}
}
I've found a solution.
All I needed to do was to play around with the strutStyle property of the TextField.
As the documentation states:
The strut style used for the vertical layout.
StrutStyle is used to establish a predictable vertical layout. Since
fonts may vary depending on user input and due to font fallback,
StrutStyle.forceStrutHeight is enabled by default to lock all lines to
the height of the base TextStyle, provided by style. This ensures the
typed text fits within the allotted space.

textScaleFactor is not using the center of my text as anchor

I have the following function
static Widget nameAvatar({String displayName, TextStyle style, double scale}) {
final firstLetter = displayName.isNotEmpty ? displayName[0].toUpperCase() : '?';
return Center(
child: Text(
firstLetter,
style: style,
textScaleFactor: 5.0,
),
);
}
Which returns a widget. I put this in a circle avatar. It's the fallback()
#override
Widget build(BuildContext context) {
if (hasPhotoURL) precacheImage(_buildPhoto(), context);
return InkWell(
onTap: () => onTap?.call(),
child: CircleAvatar(
backgroundColor: backgroundColor,
radius: radius,
backgroundImage: _buildPhoto(),
child: ConditionalWidget(
condition: !hasPhotoURL,
builderTrue: () => fallback,
),
),
);
}
But my text seems to be scaling downwards? If I remove the textScaleFactor it is aligned perfectly in the center of the circle? It's almost as if the scaling is no being done from the center of the text. How can I get this letter in the center?
I use the following texttheme
bodyText1: const TextStyle(
fontSize: 14,
color: _primaryColorLight,
fontFamily: 'Open Sans',
)