Ich habe eine App die responsive auf Android, iOS und Web sein soll. ich benutzte das Flutter Package responsive_framework. Die Version ist von 0.2 auf 1.0 gestiegen und mein Code funktioniert nicht mehr. Wie muss ich meinen Code ändern, dass es wieder funktioniert.
hier mein Code:
child: MaterialApp.router(
routeInformationParser: _patientAppRouteInformationParser,
routerDelegate: _patientAppRouterDelegate,
onGenerateTitle: (BuildContext context) =>
AppLocalizations.of(context)!.appTitle,
theme: theme.PatientAppTheme.defaultTheme(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
locale: context.select<GlobalStateProvider, Locale?>(
(globalState) => globalState.locale),
builder: (context, widget) => ResponsiveBreakpoints.builder(
child: MaxWidthBox(
maxWidth: double.infinity,
background: const ColoredBox(
color: Colors.white,
child:
SizedBox(height: what height, width: what width?),
), // does nothing?
child:
widget! // TODO: ResponsiveScaledBox(width: 1200,child: widget!), ?? how to scale
),
breakpoints: [],
breakpointsLandscape: [
const Breakpoint(
start: theme.breakPointMobileStart,
end: theme.breakPointMobileEnd,
name: MOBILE),
const Breakpoint(
start: theme.breakPointTabletStart,
end: theme.breakPointTabletEnd,
name: TABLET),
const Breakpoint(
start: theme.breakPointDesktopStart,
end: theme.breakPointDesktopEnd,
name: DESKTOP),
],
),
Und hier das neue von 1.0
Import this library into your project:
responsive_framework: ^latest_version
Add ResponsiveBreakpoints.builder to your MaterialApp or CupertinoApp. Define your own breakpoints and labels.
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
builder: (context, child) => ResponsiveBreakpoints.builder(
child: child!,
breakpoints: [
const Breakpoint(start: 0, end: 450, name: MOBILE),
const Breakpoint(start: 451, end: 800, name: TABLET),
const Breakpoint(start: 801, end: 1920, name: DESKTOP),
const Breakpoint(start: 1921, end: double.infinity, name: '4K'),
],
),
initialRoute: "/",
);
}
}
Use the labels you defined for layouts and values.
// Example: if the screen is bigger than the Mobile breakpoint, build full width AppBar icons and labels.
if (ResponsiveBreakpoints.of(context).largerThan(MOBILE))
FullWidthAppBarItems()
// Conditionals
ResponsiveBreakpoints.of(context).equals(DESKTOP)
ResponsiveBreakpoints.of(context).largerThan(MOBILE)
ResponsiveBreakpoints.of(context).smallerThan(TABLET)
...
Customization
You can define your own breakpoint labels and use them in your conditionals.
For example, if we're building a Material 3 Navigation Rail and want to expand the menu to full width once there is enough room, we can add a custom EXPAND_SIDE_PANEL breakpoint.
Assistant
Eine Möglichkeit, Ihren Code auf die neue Version von responsive_framework zu aktualisieren, besteht darin, Ihren aktuellen builder-Callback in MaterialApp.router durch den builder aus der neuesten Dokumentation zu ersetzen und die entsprechenden Breakpoints und Eigenschaften anzupassen. Hier ist Ihr aktualisierter Code:
Bei child: ResponsiveScaledBox(
width: ResponsiveValue(
steht
Exception has occurred.
FlutterError (A conditional value was caught referencing a nonexistent breakpoint.
ResponsiveValue requires a parent ResponsiveWrapper to reference breakpoints. Add a ResponsiveWrapper or remove breakpoint references.)
Assistant
Entschuldigung für das Missverständnis. Da bereits ein ResponsiveBreakpoints.builder in Ihrem Code vorhanden ist, müssen Sie ResponsiveValue nicht verwenden. Stattdessen können Sie die Breakpoints direkt über ResponsiveBreakpoints.of(context) abrufen und die Breite entsprechend anpassen. Hier ist der aktualisierte Code:
breakpoints: [
...
const Breakpoint(start: 801, end: 1920, name: DESKTOP),
const Breakpoint(start: 900, end: 900, name: 'EXPAND_SIDE_PANEL') <- Custom label.
const Breakpoint(start: 1921, end: double.infinity, name: '4K'),
...
]
Then, in our code, set the value based on the breakpoint condition.
Responsive Framework Widgets
The ResponsiveFramework includes a few custom widgets that supplement Flutter's responsive capabilities. They are showcased in the demo projects.
ResponsiveValue
ResponsiveRowColumn
ResponsiveGridView
ResponsiveScaledBox
MaxWidthBox
Legacy ReadMe (v0.2.0 and below)
ResponsiveWrapper Migration
The legacy ResponsiveWrapper combined multiple features into one widget. This made it difficult to use at times when custom behavior was required. The updated V1 implementation separates each feature into its own widget.
Responsive Framework v1 introduces some new widgets as well:
Limit the child widget to the maxWidth and paints an optional background behind the widget.
This widget is helpful for limiting the content width on large desktop displays and creating gutters on the left and right side of the page.
The remainder of the legacy ReadMe is preserved below as the concepts are still useful and used by the new widgets. ResponsiveWrapper has been deprecated and removed.
The Problem
Supporting multiple display sizes often means recreating the same layout multiple times. Under the traditional Bootstrap approach, building responsive UI is time consuming, frustrating and repetitive. Furthermore, getting everything pixel perfect is near impossible and simple edits take hours.
import 'package:flutter/material.dart';
@immutable
class Breakpoint {
final double start;
final double end;
final String? name;
final dynamic data;
class ResponsiveBreakpoints extends StatefulWidget {
final Widget child;
final List breakpoints;
/// A list of breakpoints that are active when the device is in landscape orientation.
///
/// In Flutter, the returned device orientation is not the real device orientation,
/// but is calculated based on the screen width and height.
/// This means that landscape only makes sense on devices that support
/// orientation changes. By default, landscape breakpoints are only
/// active when the [ResponsiveTargetPlatform] is Android, iOS, or Fuchsia.
/// To enable landscape breakpoints on other platforms, pass a custom
/// list of supported platforms to [landscapePlatforms].
final List? breakpointsLandscape;
/// Override list of platforms to enable landscape mode on.
/// By default, only mobile platforms support landscape mode.
/// This override exists primarily to enable custom landscape vs portrait behavior
/// and future compatibility with Fuschia.
final List? landscapePlatforms;
/// Calculate responsiveness based on the shortest
/// side of the screen, instead of the actual
/// landscape orientation.
///
/// This is useful for apps that want to avoid
/// scrolling screens and distribute their content
/// based on width/height regardless of orientation.
/// Size units can remain the same when the phone
/// is in landscape mode or portrait mode.
/// The developer needs only change a few widgets'
/// hard-coded size depending on the orientation.
/// The rest of the widgets maintain their size but
/// change the way they are displayed.
///
/// useShortestSide can be used in conjunction with
/// [breakpointsLandscape] for additional configurability.
/// Landscape breakpoints will activate when the
/// physical device is in landscape mode but base
/// calculations on the shortest side instead of
/// the actual landscape width.
final bool useShortestSide;
/// Print a visualization of the breakpoints.
final bool debugLog;
/// A wrapper widget that makes child widgets responsive.
const ResponsiveBreakpoints({
Key? key,
required this.child,
required this.breakpoints,
this.breakpointsLandscape,
this.landscapePlatforms,
this.useShortestSide = false,
this.debugLog = false,
}) : super(key: key);
static ResponsiveBreakpointsData of(BuildContext context) {
final InheritedResponsiveBreakpoints? data = context
.dependOnInheritedWidgetOfExactType();
if (data != null) return data.data;
throw FlutterError.fromParts(
[
ErrorSummary(
'ResponsiveBreakpoints.of() called with a context that does not contain ResponsiveBreakpoints.'),
ErrorDescription(
'No Responsive ancestor could be found starting from the context that was passed '
'to ResponsiveBreakpoints.of(). Place a ResponsiveBreakpoints at the root of the app '
'or supply a ResponsiveBreakpoints.builder.'),
context.describeElement('The context used was')
],
);
}
}
class ResponsiveBreakpointsState extends State
with WidgetsBindingObserver {
double windowWidth = 0;
double getWindowWidth() {
return MediaQuery.of(context).size.width;
}
/// Get enabled breakpoints based on [orientation] and [platform].
List getActiveBreakpoints() {
// If the device is landscape enabled and the current orientation is landscape, use landscape breakpoints.
if (isLandscape) {
return widget.breakpointsLandscape ?? [];
}
return widget.breakpoints;
}
/// Set [breakpoints] and [breakpointSegments].
void setBreakpoints() {
// Optimization. Only update breakpoints if dimensions have changed.
if ((windowWidth != getWindowWidth()) ||
(windowHeight != getWindowHeight()) ||
(windowWidth == 0)) {
windowWidth = getWindowWidth();
windowHeight = getWindowHeight();
breakpoints.clear();
breakpoints.addAll(getActiveBreakpoints());
breakpoints.sort(ResponsiveUtils.breakpointComparator);
}
}
@override
void initState() {
super.initState();
// Log breakpoints to console.
if (widget.debugLog) {
// Add Portrait and Landscape annotations if landscape breakpoints are provided.
if (widget.breakpointsLandscape != null) {
debugPrint('PORTRAIT');
}
ResponsiveUtils.debugLogBreakpoints(widget.breakpoints);
// Print landscape breakpoints.
if (widget.breakpointsLandscape != null) {
debugPrint('LANDSCAPE');
ResponsiveUtils.debugLogBreakpoints(widget.breakpointsLandscape);
}
}
// Dimensions are only available after first frame paint.
WidgetsBinding.instance.addObserver(this);
WidgetsBinding.instance.addPostFrameCallback((_) {
// Breakpoints must be initialized before the first frame is drawn.
setBreakpoints();
// Directly updating dimensions is safe because frame callbacks
// in initState are guaranteed.
setDimensions();
setState(() {});
});
@override
void didChangeMetrics() {
super.didChangeMetrics();
// When physical dimensions change, update state.
// The required MediaQueryData is only available
// on the next frame for physical dimension changes.
WidgetsBinding.instance.addPostFrameCallback((_) {
// Widget could be destroyed by resize. Verify widget
// exists before updating dimensions.
if (mounted) {
setBreakpoints();
setDimensions();
setState(() {});
}
});
}
@override
void didUpdateWidget(ResponsiveBreakpoints oldWidget) {
super.didUpdateWidget(oldWidget);
// When [ResponsiveWrapper]'s constructor is
// used directly in the widget tree and a parent
// MediaQueryData changes, update state.
// The screen dimensions are passed immediately.
setBreakpoints();
setDimensions();
setState(() {});
}
/// Responsive data about the current screen.
///
/// Resized and scaled values can be accessed
/// such as [ResponsiveBreakpointsData.scaledWidth].
@immutable
class ResponsiveBreakpointsData {
final double screenWidth;
final double screenHeight;
final Breakpoint breakpoint;
final List breakpoints;
final bool isMobile;
final bool isPhone;
final bool isTablet;
final bool isDesktop;
final Orientation orientation;
/// Creates responsive data with explicit values.
///
/// Alternatively, use [ResponsiveBreakpointsData.fromResponsiveWrapper]
/// to create data based on the [ResponsiveBreakpoints] state.
const ResponsiveBreakpointsData({
this.screenWidth = 0,
this.screenHeight = 0,
this.breakpoint = const Breakpoint(start: 0, end: 0),
this.breakpoints = const [],
this.isMobile = false,
this.isPhone = false,
this.isTablet = false,
this.isDesktop = false,
this.orientation = Orientation.portrait,
});
/// Returns if the active breakpoint is [name].
bool equals(String name) => breakpoint.name == name;
/// Is the [screenWidth] larger than [name]?
/// Defaults to false if the [name] cannot be found.
bool largerThan(String name) =>
screenWidth >
(breakpoints.firstWhereOrNull((element) => element.name == name)?.end ??
double.infinity);
/// Is the [screenWidth] larger than or equal to [name]?
/// Defaults to false if the [name] cannot be found.
bool largerOrEqualTo(String name) =>
screenWidth >=
(breakpoints.firstWhereOrNull((element) => element.name == name)?.start ??
double.infinity);
/// Is the [screenWidth] smaller than the [name]?
/// Defaults to false if the [name] cannot be found.
bool smallerThan(String name) =>
screenWidth <
(breakpoints.firstWhereOrNull((element) => element.name == name)?.start ??
0);
/// Is the [screenWidth] smaller than or equal to the [name]?
/// Defaults to false if the [name] cannot be found.
bool smallerOrEqualTo(String name) =>
screenWidth <=
(breakpoints.firstWhereOrNull((element) => element.name == name)?.end ??
0);
/// Is the [screenWidth] smaller than or equal to the [name]?
/// Defaults to false if the [name] cannot be found.
bool between(String name, String name1) {
return (screenWidth >=
(breakpoints
.firstWhereOrNull((element) => element.name == name)
?.start ??
0) &&
screenWidth <=
(breakpoints
.firstWhereOrNull((element) => element.name == name1)
?.end ??
0));
}
@override
int get hashCode =>
screenWidth.hashCode * screenHeight.hashCode * breakpoint.hashCode;
}
/// Creates an immutable widget that exposes [ResponsiveBreakpointsData]
/// to child widgets.
///
/// Access values such as the [ResponsiveBreakpointsData.scaledWidth]
/// property through [ResponsiveBreakpoints.of]
/// ResponsiveWrapper.of(context).scaledWidth.
///
/// Querying this widget with [ResponsiveBreakpoints.of]
/// creates a dependency that causes an automatic
/// rebuild whenever the [ResponsiveBreakpointsData]
/// changes.
///
/// If no [ResponsiveBreakpoints] is in scope then the
/// [MediaQuery.of] method will throw an exception,
/// unless the nullOk argument is set to true, in
/// which case it returns null.
@immutable
class InheritedResponsiveBreakpoints extends InheritedWidget {
final ResponsiveBreakpointsData data;
/// Creates a widget that provides [ResponsiveBreakpointsData] to its descendants.
///
/// The [data] and [child] arguments must not be null.
const InheritedResponsiveBreakpoints(
{Key? key, required this.data, required Widget child})
: super(key: key, child: child);
@override
bool updateShouldNotify(InheritedResponsiveBreakpoints oldWidget) =>
data != oldWidget.data;
}
Ich habe die background-Eigenschaft in MaxWidthBox aktualisiert, um die Größe für SizedBox anzugeben, und die breakpointsLandscape durch breakpoints ersetzt. Sie können die Größe entsprechend Ihren Bedürfnissen anpassen.
Stellen Sie sicher, dass Sie die neueste Version des responsive_framework-Pakets in Ihrer pubspec.yaml aufgenommen haben:
dependencies:
responsive_framework: ^1.0.0
Auch sollten Sie landscapePlatforms, useShortestSide und debugLog Eigenschaften hinzufügen, wenn Sie sie verwenden möchten.
Wie fixe ich den Code, dass er funktioniert:
child: MaterialApp.router(
routeInformationParser: _patientAppRouteInformationParser,
routerDelegate: _patientAppRouterDelegate,
onGenerateTitle: (BuildContext context) =>
AppLocalizations.of(context)!.appTitle,
theme: theme.PatientAppTheme.defaultTheme(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
locale: context.select<GlobalStateProvider, Locale?>(
(globalState) => globalState.locale),
builder: (context, widget) => ResponsiveBreakpoints.builder(
child: MaxWidthBox(
maxWidth: 1200,
background: Container(color: const Color(0xFFF5F5F5)),
child: ResponsiveScaledBox(
// ResponsiveScaledBox renders its child with a FittedBox set to the width value.
// Set the fixed width value based on the active breakpoint.
width: ResponsiveValue(context, conditionalValues: [
const Condition.equals(name: MOBILE, value: 450),
const Condition.between(start: 800, end: 1100, value: 800),
const Condition.between(start: 1000, end: 1200, value: 1000),
// There are no conditions for width over 1200
// because the maxWidth is set to 1200 via the MaxWidthBox.
]).value,
child: widget!),
),
breakpoints: [
const Breakpoint(
start: theme.breakPointMobileStart,
end: theme.breakPointMobileEnd,
name: MOBILE),
const Breakpoint(
start: theme.breakPointTabletStart,
end: theme.breakPointTabletEnd,
name: TABLET),
const Breakpoint(
start: theme.breakPointDesktopStart,
end: theme.breakPointDesktopEnd,
name: DESKTOP),
const Breakpoint(start: 1921, end: double.infinity, name: '4K')
],
),
),
Transferiere den code von unten auf meinen Code
sollte so wie das funktionieren:
return MaterialApp(
// Wrapping the app with a builder method makes breakpoints
// accessible throughout the widget tree.
builder: (context, child) => ResponsiveBreakpoints.builder(
child: child!,
breakpoints: [
const Breakpoint(start: 0, end: 450, name: MOBILE),
const Breakpoint(start: 451, end: 800, name: TABLET),
const Breakpoint(start: 801, end: 1920, name: DESKTOP),
const Breakpoint(start: 1921, end: double.infinity, name: '4K'),
],
),
initialRoute: '/',
// The following code implements the legacy ResponsiveWrapper AutoScale functionality
// using the new ResponsiveScaledBox. The ResponsiveScaledBox widget preserves
// the legacy ResponsiveWrapper behavior, scaling the UI instead of resizing.
//
// A ConditionalRouteWidget is used to showcase how to disable the AutoScale
// behavior for a page.
onGenerateRoute: (RouteSettings settings) {
// A custom fadeThrough route transition animation.
return Routes.fadeThrough(settings, (context) {
// Wrap widgets with another widget based on the route.
// Wrap the page with the ResponsiveScaledBox for desired pages.
return ConditionalRouteWidget(
routesExcluded: const [
TypographyPage.name
], // Excluding a page from AutoScale.
builder: (context, child) => MaxWidthBox(
// A widget that limits the maximum width.
// This is used to create a gutter area on either side of the content.
maxWidth: 1200,
background: Container(color: const Color(0xFFF5F5F5)),
child: ResponsiveScaledBox(
// ResponsiveScaledBox renders its child with a FittedBox set to the width value.
// Set the fixed width value based on the active breakpoint.
width: ResponsiveValue(context,
conditionalValues: [
const Condition.equals(name: MOBILE, value: 450),
const Condition.between(
start: 800, end: 1100, value: 800),
const Condition.between(
start: 1000, end: 1200, value: 1000),
// There are no conditions for width over 1200
// because the maxWidth is set to 1200 via the MaxWidthBox.
]).value,
child: child!),
),
In diesem aktualisierten Code habe ich ResponsiveBreakpoints.builder genauso verwendet wie im Beispiel, aber ich habe die breakpoints-Liste entsprechend Ihren aktuellen Einstellungen angepasst. Außerdem wird der MaxWidthBox-Wrapper verwendet, um den Hintergrund und die Maximalbreite festzulegen und ResponsiveScaledBox ist eingeschlossen, um die Breite entsprechend den Bedingungen anzupassen.
In diesem aktualisierten Code habe ich einen Builder um ResponsiveScaledBox hinzugefügt, um auf ResponsiveBreakpoints.of(context) zugreifen und die benötigte Breite auf der Grundlage der aktiven Breakpoints direkt zu berechnen.